pygame 绘制带裁剪区域的生命条

pygame draw lifebar with a clipping area

我想用pygame画一个lifebar,使用裁剪区域(例如,当一半生命值消失时,将区域限制为一半。) 但是即使裁剪区域是正确的,我总是得到完整的图像。

那是我的生命线class:

class Lifebar():
    def __init__(self,x,y,images,owner):
        self.x=x
        self.y=y
        self.images=images
        self.owner=owner
        self.owner.world.game.addGUI(self)
        self.inter=False

    def getValues(self):
        value1 = 1.0 * self.owner.hitpoints
        value2 = 1.0 * self.owner.maxhitpoints
        return [value1,value2]

    def render(self,surface):
        rendervalues = self.getValues()
        maxwidth = self.images[0].get_width()
        ratio = rendervalues[0] / rendervalues[1]
        actwidth = int(round(maxwidth * ratio))
        surface.blit(self.images[0],(self.x,self.y))
        surface.set_clip(self.x, 0, (self.x+actwidth), 1080)
        surface.blit(self.images[1],(self.x,self.y))
        self.owner.world.game.setclipDefault()
        surface.blit(self.images[2],(self.x,self.y))

我检查过生命值没有满,剪裁区域在 x 方向上是有限的。 (get_clip()) 我不知道我是否误解了 set_clip() 的工作原理,因为我之前只将它用于整个屏幕(部分超出屏幕的对象)

pygame.Surface 对象的 .set_clip() 方法 设置当您调用 .blit() 时任何其他表面将被绘制到的区域 .这意味着传递的矩形 定义了目标表面上的新原点 以及将要更新的区域的大小。

剪切图像的特定区域并将其绘制到表面上,您可以将可选的矩形作为第三个参数传递给.blit()方法:

surface.blit(source_image, #source image (surface) which you want to cut out
             (destination_x, destination_y), #coordinates on the destination surface
             (x_coordinate, y_coordinate, width, height)) #"cut out"-rect

希望对您有所帮助:)