【问题标题】:Pygame using sprite sheet : alpha problemsPygame 使用精灵表:alpha 问题
【发布时间】:2018-01-04 11:57:57
【问题描述】:

我正在使用精灵表为我的播放器设置动画,动画效果很好,但是当我在屏幕上对动画的相应图像进行 blit 时没有 alpha。

Class Animation:
    def __init__(self, path, img_size):
        self.images = pyagme.image.load(path).convert_alpha()
        self.cur_img = 0
        ....

    def get_image(self):
        img=pygame.Surface((self.img_width,self.img_height)).convert_alpha()
        rect = pygame.Rect((self.cur_img * self.img_width, 0),(self.img_width, self.img_height))
        img.blit(self.images, (0, 0), rect)
        return img

我正在使用get_image 函数来绘制玩家: 每次更新:self.image = self.cur_anim.get_image()self 是 Player 类。

在我的函数drawself.screen.blit(self.player.image, self.player.rect)

【问题讨论】:

  • 新 Surface 永远不会透明,您必须使用具有A=0 的 RGBA 颜色 fill() - 参见示例 transparency。但是您可以使用Surface.subsurface 创建img,并且不需要新的Surface。顺便说一句,您可以在__init__ 中创建所有子表面并保留在列表中,然后您可以获得img = self.all_images[self.cur_img] - 参见示例spritesheet

标签: python pygame


【解决方案1】:

新的Surface 永远不会透明,因此您必须使用具有A=0RGBA 颜色填充它以使其透明。

img = pygame.Surface((self.img_width,self.img_height)).convert_alpha()

img.fill( (0,0,0,0) )

但是有pygame.Surface.subsurface可以创建子图像(并且它不使用新内存)

def get_image(self):
    rect = pygame.Rect((self.cur_img * self.img_width, 0),(self.img_width, self.img_height))

    return self.images.subsurface(rect)

顺便说一句:您可以在 __init__ 中创建所有子表面,然后仅使用

def get_image(self):
    return self.all_subsurfaces[self.cur_img]

【讨论】:

  • 您也可以通过pygame.SRCALPHA 来获得具有每像素alpha 的透明表面:img = pygame.Surface((self.img_width, self.img_height), pygame.SRCALPHA)
猜你喜欢
  • 2021-05-23
  • 2023-03-23
  • 2014-01-13
  • 2023-03-05
  • 2013-06-12
  • 1970-01-01
  • 2023-03-02
  • 2019-03-23
  • 1970-01-01
相关资源
最近更新 更多