你需要追踪时间,因此可以使用
pygame.time.get_ticks
或者
clock.tick()
返回的时间(通常称为
dt
,即增量时间),然后在经过一定时间后更新图像。
pygame.time.get_ticks
变体:
class Player(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.frame = 0
self.image = IMAGES[self.frame]
self.rect = self.image.get_rect(center=pos)
self.start_time = pg.time.get_ticks()
self.time_limit = 300
def update(self):
now = pg.time.get_ticks()
if now - self.start_time > self.time_limit:
self.frame += 1
self.frame %= len(IMAGES)
self.image = IMAGES[self.frame]
self.start_time = now
以下是带有时间增量变量的完整示例。 (您的类中无论如何都需要dt
以获取移动速度,如果您最终想要使游戏帧率独立)。
import pygame as pg
IMAGE1 = pg.Surface((90, 90))
IMAGE1.fill((30, 90, 200))
pg.draw.circle(IMAGE1, (50, 170, 220), (45, 45), 15)
IMAGE2 = pg.Surface((90, 90))
IMAGE2.fill((30, 90, 200))
pg.draw.circle(IMAGE2, (50, 170, 220), (30, 30), 15)
pg.draw.circle(IMAGE2, (50, 170, 220), (60, 60), 15)
IMAGE3 = pg.Surface((90, 90))
IMAGE3.fill((30, 90, 200))
pg.draw.circle(IMAGE3, (50, 170, 220), (20, 20), 15)
pg.draw.circle(IMAGE3, (50, 170, 220), (45, 45), 15)
pg.draw.circle(IMAGE3, (50, 170, 220), (70, 70), 15)
IMAGES = [IMAGE1, IMAGE2, IMAGE3]
class Entity(pg.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups)
self.frame = 0
self.image = IMAGES[self.frame]
self.rect = self.image.get_rect(center=pos)
self.timer = 0
def update(self, dt):
self.timer += dt
if self.timer >= .5:
self.timer = 0
self.frame += 1
self.frame %= len(IMAGES)
self.image = IMAGES[self.frame]
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group(Entity((200, 200)))
dt = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
all_sprites.update(dt)
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
dt = clock.tick(30) / 1000
if __name__ == '__main__':
pg.init()
main()
pg.quit()
time.sleep(time)
方法,它会让你的程序休眠传递给它的time
时间。 - Professor_Joykill