我正试图在pygame中制作一把剑“摇摆”。我或多或少地使用这样的方法。
def animate(self):
self.image1 = pg.Surface((40, 30))
self.image1.fill(255,0,0)
self.image2 = pg.Surface((60, 20))
self.image2.fill(0,0,255)
self.image = self.image1
#not the real images, but you get the point
now = pg.time.get_ticks()
keys = pg.key.get_pressed()
if keys[pg.K_l] or keys[pg.K_j]:
self.slashing = True
else:
self.slashing = False
#player image starts out as self.image1
if self.slashing:
self.image = self.image2
if now - self.last_slash > 750:
self.last_slash = now
self.image = self.image1
它正在交换图像2,但是我的计时器并没有像我希望的那样带回图像。它只是像image2一样。
答案 0 :(得分:0)
如果您只想切换两张图像,可以执行以下操作:当用户斜杠时,将self.image
设置为第二张剑图像,当时间到了或用户释放密钥时,重置self.image
到第一张剑形象。我认为在这种情况下使用事件循环并在类中处理事件会更容易。
import pygame as pg
# Two sword images.
SWORD_IMG1 = pg.Surface((140, 140), pg.SRCALPHA)
pg.draw.polygon(
SWORD_IMG1, pg.Color('lightskyblue1'),
((70, 0), (76, 10), (76, 70), (64, 70), (64, 10)))
SWORD_IMG2 = pg.transform.rotozoom(SWORD_IMG1, -90, 1)
class Sword(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.image = SWORD_IMG1
self.rect = self.image.get_rect(center=pos)
self.slashing = False
self.last_slash = None
def handle_event(self, event):
if event.type == pg.KEYDOWN:
if event.key in (pg.K_j, pg.K_l):
if not self.slashing:
# Start the slashing animation.
self.image = SWORD_IMG2 # Set the image.
self.slashing = True
self.last_slash = pg.time.get_ticks()
elif event.type == pg.KEYUP:
if event.key in (pg.K_j, pg.K_l):
# Reset the image.
self.image = SWORD_IMG1
self.slashing = False
def update(self):
# The update method gets called once each frame.
if self.slashing:
self.animate()
def animate(self):
now = pg.time.get_ticks()
if now - self.last_slash > 750:
# When the anim is done, reset the image.
self.image = SWORD_IMG1
self.slashing = False
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
sword = Sword((100, 300), all_sprites)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
sword.handle_event(event)
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()