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

标签 python python-3.x pygame sprite

我正在尝试使用 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. 然后,在更新函数内部:在原始图像上设置剪辑,获取新图像,并将其存储在图像中(自动绘制到屏幕上的图像) .

    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/

相关文章:

python - 如何通过 python API 将 json/pickle 文件转储和读取到 Google Drive?

python - 用数字自身替换每个字母

python - pyx 模块 : how to make color transparent

python - 如何在游戏中模拟浮力?

Python:导入matplotlib但无法使用imshow

python - 定位列表中重复项的位置及其位置

Python\SQLite : table A has no column named X

python - 设置正则表达式模式,如果该模式在字符串中得到验证,则其中的一部分将被另一个子字符串替换

python - Pygame 如何显示变量?

python - Pygame 滚动条播放音量低还是高。?