How do I get the position of a sprite in Pygame?

Question:

So I’m trying to programme a mouse that moves to the nearest pieces of cheese near it on the screen and eat it. However, in order to do so, I would need to find the positions/coordinates of other sprites. So how would I find the position of a sprite in Pygame? Thanks!

Asked By: oceandye

||

Answers:

According to the documentation each sprite requires to have a .rect attribute.
See the documentation of pygame.sprite:

The basic Sprite class can draw the Sprites it contains to a Surface. The Group.draw() method requires that each Sprite have a Surface.image attribute and a Surface.rect.

The .rect attribute has to be set by the application:

Again I’ll refer to the documentation:

When subclassing the Sprite, be sure to call the base initializer before adding the Sprite to Groups. For example:

class Block(pygame.sprite.Sprite):

    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, color, width, height):
       # Call the parent class (Sprite) constructor
       pygame.sprite.Sprite.__init__(self)

       # Create an image of the block, and fill it with a color.
       # This could also be an image loaded from the disk.
       self.image = pygame.Surface([width, height])
       self.image.fill(color)

       # Fetch the rectangle object that has the dimensions of the image
       # Update the position of this object by setting the values of rect.x and rect.y
       self.rect = self.image.get_rect()

Of course the attributes can be directly set to the sprite object, too:

e.g.

mySprite = pygame.sprite.Sprite()
mySprite.image = pygame.Surface([width, height])
mySprite.rect = mySprite.image.get_rect()

After that the position can be get from the .rect attribute at any time. See pygame.Rect:

e.g.

topLeftX, tolLeftY = mySprite.rect.topleft
centerX, centerY = mySprite.rect.center
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.