Timmy
Timmy

Reputation: 81

How can I get the coordinates of a sprite's position in pygame?

What' I'm trying to do is prevent my sprite from going off the borders in a game I'm writing. It should be very simple, here is some pseudo-code of what my program does so far.

rect = my_sprite_img.get_rect()
while (1)
    if keydown = left:
        direction = [-30,0]
    elif keydown = right:
        direction = [30,0]
    rect = rect.move(direction)
    screen.blit(mysprite_img, rect)

Again, this is not my real code just a super simple example. All I want to be able to do is to say
"If rect.position.x < 0 : don't move left"
Is there a built in function that gives me the coordinates of a rect, because I haven't been able to find one by looking at http://www.pygame.org/docs/ref/rect.html

Thanks in advance.

Upvotes: 5

Views: 25182

Answers (1)

FogleBird
FogleBird

Reputation: 76792

See the documentation here:

http://www.pygame.org/docs/ref/rect.html

The Rect object has several virtual attributes which can be used to move and align the Rect:

top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w, h

So, you can use rect.left for the x coordinate, and rect.top for the y coordinate. These are attributes, not functions.

Upvotes: 8

Related Questions