python - 如何在 Pygame 中获取 Sprite 的位置?

标签 python pygame

所以我正在尝试对一只鼠标进行编程,让它移动到屏幕上离它最近的奶酪 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 a Surface.image attribute and a Surface.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/

相关文章:

python - 继承模型元类的正确语法?

python 不会长大

python - 反向 'update' 关键字参数 '{' id' : '' }' not found. 1 pattern(s) tried: [' update/(? P<id>[0-9]+)/\\Z']

python - 在 Pygame 中使用 Sprite 进行碰撞检测

python - 如何使对象在按键时在对象数组中移动?

python - cvtColor 断言失败 scn == 3 || scn ==4,但是图像确实有3个 channel 并且存在

python-3.x - 使文本适合 pygame 中的现有表面

python - Keras属性错误: 'Tensor' object has no attribute 'log'

Python访问错误类的属性

python - 从多个 url 的 csv 列表打印 JSON 数据