所以我正在尝试对一只鼠标进行编程,让它移动到屏幕上离它最近的奶酪 block 并吃掉它。然而,为了做到这一点,我需要找到其他 Sprite 的位置/坐标。那么我如何在 Pygame 中找到 Sprite 的位置呢?谢谢!
最佳答案
根据文档,每个 Sprite 都需要有一个 .rect
属性。
请参阅 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
.
.rect
属性必须由应用程序设置:
我再次引用文档:
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()
当然也可以直接给 Sprite 对象设置属性:
例如
mySprite = pygame.sprite.Sprite()
mySprite.image = pygame.Surface([width, height])
mySprite.rect = mySprite.image.get_rect()
之后可以随时从 .rect
属性获取位置。请参阅pygame.Rect
:
例如
topLeftX, tolLeftY = mySprite.rect.topleft
centerX, centerY = mySprite.rect.center
关于python - 如何在 Pygame 中获取 Sprite 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55321669/