您的位置:首页 > 其它

pygame库写游戏——入门<8>——动画和帧率

2017-12-10 12:21 260 查看
理解帧率

FPS(Frame Per Second),一般电视画面是24FPS,30FPS基本可提供流畅的体验,60FPS是LCD常用的刷新率;而绝大多数人无法分辨70FPS以上的画面。

直线运动

尝试让hello world程序中的鱼动起来:

background_filename = 'sushiplate.jpg'
mouse_filename = 'fugu.png'

import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((640,480),RESIZABLE,32)
mouse_cursor = pygame.display.set_caption('hello world!')

background = pygame.image.load(background_filename).convert()
mouse_cursor = pygame.image.load(mouse_filename).convert_alpha()
x == 0
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
pygame.quit()
if event.type == VIDEORESIZE:
SCREEN_SIZE = event.size
screen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32)

screen_width, screen_height = SCREEN_SIZE

screen.blit(background,(0,0))
screen.blit(mouse_cursor,(x,240))
x += 1
if x > 640:
x = 0
pygame.display.update()


可以调节x +=1来改变鱼的运行速度。

有些时候动画的元素很多,就会导致电脑的运行速率下降,我们要尽量避免这样的情况。

关于时间

解决上一个问题的方法之一就是让动画基于时间运作——需要知道上一个画面到现在经过了多长的时间,然后我们决定是否开始绘制下一幅图。而pygame.time模块就给我们提供了一个Clock对象,使我们轻易做到这一点:

clock = pygame.time.Clock()
#初始化Clock对象
time_passed = clock.tick()
#返回上一个调用的时间(ms)
time_passed = clock.tick(30)
#在么一个循环中加上它,其中的参数就成为了游戏的最大帧率,避免游戏占用所有的CPU资源。


虽然可以设定最大的帧率,但是有些机器性能不足,实际帧率达不到如上效果,因此需要用另一个手段来控制。

为了使在不同的设备上有一只的效果,我们其实需要给定物体恒定的速度(精灵Sprite),这样从起点到终点的时间就是一样的,最终效果也就相同了,差别仅仅在于流畅度。



试用上面的结论,假设需要小鱼每秒运动250像素,游完一个屏幕需要大概2.56秒,这样,我们就需要知道从上一帧开始到现在,小鱼运动了多少像素,即速度*时间,250*time_passed_second。不过时间单位是ms,需要除以1000。

程序可改为:

# -*- coding: utf-8 -*-
"""
Created on Tue Dec  5 14:42:51 2017

@author: zhang
"""

background_filename = 'sushiplate.jpg'
mouse_filename = 'fugu.png'

import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((640,480),RESIZABLE,32)
mouse_cursor = pygame.display.set_caption('hello world!')

background = pygame.image.load(background_filename).convert()
mouse_cursor = pygame.image.load(mouse_filename).convert_alpha()

clock = pygame.time.Clock()
x = 0
speed = 250
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
pygame.quit()
if event.type == VIDEORESIZE:
SCREEN_SIZE = event.size
screen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32)

screen_width, screen_height = SCREEN_SIZE

screen.blit(background,(0,0))
screen.blit(mouse_cursor,(x,100))

time_passed = clock.tick()
time_passed_seconds = time_passed / 1000
distance = speed * time_passed_seconds

x += distance
if x > 640:
x -= 640
pygame.display.update()


斜线运动

即加上speed_y的程序片段即可。

同时可以使用片段

if x > 640:
speed = -speed
elif x < 0:
speed = -speed


来做到使小球碰壁即反弹。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动画 游戏