Reputation: 319
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!
Upvotes: 2
Views: 5859
Reputation: 210889
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 aSurface.image
attribute and aSurface.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
Upvotes: 2