直线运动
实现方式相当简单,其实就是用bilt函数不停地该变坐标即可,比如
# sprite的起始坐标
x = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0, 0))
screen.blit(sprite, (x, 100))
x += 1
if x>640:
x = 0
pygame.display.update()
控制帧率
在上面的程序中,帧率是很高的。而且电脑的性能不同,鱼的速度就会不同,如果动画的的元素很多,速度就会下降。
为了解决这个问题,可以使用pygame的时间模块。
clock = pygame.time.Clock()
time_passed = clock.tick()
time_passed = clock.tick(30)
第一行初始化了一个Clock对象。第二行返回了距上一次调用这个函数,过去了多长时间(注意,得到的值是以毫秒为单位的)。第三行,在函数中添加了framerate参数,这个函数会延时使得游戏的帧率不会超过给定值。
给定的值仅仅是最大帧率,当动作复杂或机器性能不足时,实际帧率无法达到这个值,需要一种手段控制动画效果。比如给物体一个恒定的速度,再通过时间,计算出移动的距离。
斜线运动
这个原理也很简单,做一个触边速度变更的逻辑判断即可
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0, 0))
screen.blit(sprite, (x, y))
time_passed = clock.tick(30)
time_passed_seconds = time_passed/1000
x += speed_x * time_passed_seconds
y += speed_y * time_passed_seconds
# 到达边界后速度反向
if x > 640 - sprite.get_width():
speed_x = -speed_x
x = 640 - sprite.get_width()
elif x < 0:
speed_x = -speed_x
x = 0
if y > 480 - sprite.get_height():
speed_y = -speed_y
y = 480 - sprite.get_height()
elif y < 0:
speed_y = -speed_y
y = 0
pygame.display.update()
为了代码优雅,可以使用向量来完成上述目标,不过这可能需要自己码一个模块来完成这个目标。