我在 Python 和 Pygame 中加载了一个包含不同大小的精灵的精灵表。我可以显示它们,但即使它是空闲动画,角色也不会静止不动,因为有些动画更大,因此会迫使角色更靠右。
我的代码是:
class Hero(pygame.sprite.Sprite):
"""Hero class"""
def __init__(self, position):
pygame.sprite.Sprite.__init__(self)
self.load_frames()
self.image = self.img_list[0]
self.rect = self.image.get_rect()
self.rect.topleft = position
self.pause = 1
self.delay = 1
self.index = 0
def load_frames(self):
spritesheet = pygame.image.load("spritesheet.png").convert()
self.img_list = []
self.size_list = [(26,32),(27,31),(29,30), (31,30), (33,31), (34,31), (36,32), (38,33), (34,33), (34,33), (32,32), (27,31), (25,30), (24,30), (23,31), (21,31), (20,32), (20,33), (22,33), (24,33)]
self.offset = ((14,6), (42,7), (72,8), (104,8), (138,7), (174,7), (211,6), (250,5), (291,5), (328,5), (365,5), (400,6), (430,8), (458,8), (485,7), (511,7), (535,5), (558,4), (581,4), (606,4))
for i in range(20):
tmp_img = pygame.Surface(self.size_list[i])
tmp_img.blit(spritesheet, (0,0), (self.offset[i], self.size_list[i]))
self.img_list.append(tmp_img)
def update(self):
if self.delay == self.pause:
if self.index == len(self.img_list):
self.index = 0
oldcenter = self.rect.center
self.image = self.img_list[self.index]
self.rect = self.image.get_rect()
self.rect.center = oldcenter
self.delay = 0
self.index += 1
self.delay += 0.5
即使精灵大小不同,我如何使角色居中?我的第一个想法是以某种方式制作一个我手动定位的参考点,但这似乎有点慢,有没有更好的方法,或者如果这是一个好方法,我将如何实现它?