通过在Pygame中使用Group类来绘制区域或部分精灵

问题描述:

我想要使用Sprite模块中的Group类绘制一个区域或部分精灵。通过在Pygame中使用Group类来绘制区域或部分精灵

所以我有这个类来处理我的精灵:
(...是的,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) 

然后,我上传使用精灵:

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

最后,我通过使用spriteGroup.draw(source)

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

集团子类RenderUpdatesdraw()方法,所以它不会接受这种参数...同时,Surface.blit()(即使我可以用它)是不是一种选择,因为blit()预计坐标绘制来源,但我已经从上面的课程中定义了这些。

所以......我怎么能通过像(0, 0, 75, 75)这样的参数分别表示我的精灵的第一个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() 
    

你的精灵的图像尺寸是100×100,从原始图像的原点测量。你可以拨弄pygame.Rect里面的set_clip得到你想要的图像。

+0

你是个天才!我读了关于set_clip(),但我不知道如何在我的精灵上使用它...原始图像。感谢您的帮助! –

我找到了解决这个问题的方法。其实,set_clip()方法不起作用。这是我的方式使用image.subsurfacedoc

subsurface() 
    create a new surface that references its parent 
    subsurface(Rect) -> Surface 

在您的代码中,您可以尝试以下操作来绘制Rect(0,0,75,75)

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

     self.original = pygame.image.load(player) 
     self.original = pygame.transform.scale(self.image, (300, 75)) 
     self.image = self.original.subsurface(Rect(0, 0, 75, 75)) 
     self.rect = self.image.get_rect() 

然后,更新self.imageself.rectupdate函数中。