gpt4 book ai didi

python - 在 Pygame 中使用 Group 类绘制 Sprite 的区域或部分

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:56 24 4
gpt4 key购买 nike

我正在尝试使用 sprite 模块中的 Group 类绘制一个区域或部分 sprite。

所以我有这个类来处理我的 Sprite :
(...是的,pygame 已经导入。)

class Sprite(pygame.sprite.Sprite):
def __init__(self, player):
pygame.sprite.Sprite.__init__(self)

self.image = pygame.image.load(player)
self.image = pygame.transform.scale(self.image, (300, 75))

startPoint = (100, 500)
self.rect = self.image.get_rect()
self.rect.bottomleft = (startPoint)

然后,我使用以下方法上传 Sprite :

someFile = Sprite(join('res', 'file.png'))
spriteGroup = pygame.sprite.RenderUpdates(someFile)

最后,我使用spriteGroup.draw(source)绘制了它

但是,我的问题是我只想绘制一小块区域或原始文件图像的一部分。现在,我知道使用 Surface.blit() 我可以传递一个可选区域矩形,代表要绘制的源 Surface 的较小部分。

Group 子类 RenderUpdates 有一个 draw() 方法,所以它不接受这种参数...还有,Surface.blit ()(即使我可以使用它)不是一个选项,因为 blit() 期望坐标绘制源,但我已经在我的类中从上面定义了这些。

所以...我如何传递诸如 (0, 0, 75, 75) 之类的参数来分别表示我的 Sprite 的第一个 x 和 y、宽度和高度以仅绘制那部分?

最佳答案

这是我的建议。

  1. 在您的 __init__ 函数中,将图像存储在 2 个变量中。

    # Stores the original image
    self.ogimage = pygame.image.load(player)
    self.ogimage = pygame.transform.scale(self.image, (300, 75))
    # Stores the image that is displayed to the screen
    self.image = self.ogimage
  2. 然后,在 update 函数内部:在原始图像上设置剪辑,获取新图像,并将其存储在图像(自动绘制到屏幕的图像)中.

    def update(self):
    self.ogimage.set_clip(pygame.Rect(0, 0, 100, 100))
    self.image = self.ogimage.get_clip()

您的 sprite 图像现在大小为 100x100,从原始图像的原点开始测量。您可以在 set_clip 中摆弄 pygame.Rect 以获得您想要的图像。

关于python - 在 Pygame 中使用 Group 类绘制 Sprite 的区域或部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43233956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com