游戏中我们尽量使运动的物体与现实相近,得到强大的游戏代入感,故我们需要开始学习游戏的动画制作,只有活动起来的画面才能更加吸引人
我们知道游戏的画面感是否强大取决于其是否流畅,感官不突兀,故我们需要一定的帧率来决定,即FPS
首先介绍几个常用的量
帧率 | 一般设备 |
---|---|
24FPS | 电视画面 |
30FPS | 流畅的游戏体验 |
60FPS | LCD中常用的刷新率 |
70FPS及以上 | 正常人眼无法辨别 |
一、直线运动
直接设定其初始坐标x =0然后在图上显示,在循环中,x一直以固定频率增加,知道达到边界回到起始位置
这个就为最简单的直线运动
p = 0
while True:
screen.blit(sprite, (p,100))
p += 10
if p > 400:
p = 0
效果如下:(兔子可一直运动)
但是我们可以观察到兔子运动的一点都不自然
这就关系到我们的时间问题了
时间
先以一段代码为例:
#初始化一个Clock对象
clock = pygame.time.Clock()
#返回一个上次调用的时间
time_passed = clock.tick()
#在循环中使用,其中tick中的参数就是游戏绘制的最大帧率
time_passec = clock.tick(30)
而如果机器性能不好或者动画太复杂,是达不到我们的最大帧率的
故我们通过速度来控制
代码如下:
#Clock对象
clock = pygame.time.Clock()
p = 0
speed = 250
while True:
screen.blit(sprite, (p,100))
time_passed = clock.tick()
time_passed_seconds = time_passed/1000.0
#由于得到的单位是毫秒
distance_moved = time_passed_seconds*speed
p += distance_moved
if p > 640:
p -= 640
实际差别并不明显,但是很多情况下时间控制比直接调节帧率好得多
二、斜线运动
即不只是一个方向的直线运动,碰了壁会反弹,实际也只是在碰壁之后将速度取反而已
部分代码如下:
#Clock对象
clock = pygame.time.Clock()
p,q = 100,100
speed_x , speed_y = 133, 170
while True:
screen.blit(sprite, (p, q))
time_passed = clock.tick(30)
time_passed_seconds = time_passed/1000.0
#由于得到的单位是毫秒
p += speed_x*time_passed_seconds
q += speed_y*time_passed_seconds
if p > 580-sprite.get_width():
speed_x = -speed_x
p = 580-sprite.get_width()
elif p < 0:
speed_x = -speed_x
p = 0
if q > 400-sprite.get_height():
speed_y = -speed_y
q = 400-sprite.get_height()
elif q < 0:
speed_y = -speed_y
q = 0
效果图如下:
看到这里我们可能就明白了所谓pygame中的2D游戏实际就是坐标的改变,一直不停的在计算和增减坐标,故我们需要向量来为我们减少负担
三、向量
在学习向量之前我们需要安装一个插件game objects
可以参看我的第一篇安装插件的博客
在安装完之后可以用这些代码来测试是否安装成功
先导入game objects
from gameobjects.vector2 import *
若是三维向量就调用vector3
再定义向量
A = (10.0, 20.0)
B = (30.0, 35.0)
AB = Vector2.from_points(A, B)
打印输出相应的值即可
print("Vector AB is " , AB )
print("AB + (-10, 5) is ", AB +(-10,5))
print("AB*2 is " , AB*2)
#对于该向量相除仍报错,目前还没找到原因
print("AB/2 is " , AB/2)
print("Magnitude of AB is " , AB.get_magnitude())
print("AB normalised is " , AB.get_normalised())
输出为:
Vector AB is ( 20 , 15 )
AB + (-10, 5) is ( 10 , 20 )
AB*2 is ( 40 , 30 )
AB/2 is AB/2
Magnitude of AB is 25.0
AB normalised is ( 0.8 , 0.6 )
在学习了基本的向量之后,我们现在可以对我们的兔子程序进行进一步的修改
部分代码如下:
clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)
heading = Vector2()
while True:
width = sprite.get_width()
height = sprite.get_height()
screen.blit(sprite, position)
time_passed = clock.tick()
time_passed_seconds = time_passed/1000.0
#参数前面加*意味着将列表或元组展开
destination = Vector2(*pygame.mouse.get_pos() ) - Vector2(width/2, height/2)
#计算鱼儿当前位置到鼠标位置的向量
vector_to_mouse = Vector2.from_points(position, destination)
#向量规格化
vector_to_mouse.normalise()
#heading可看作兔子的速度,在没有到鼠标时加速,超过则减速
#则可看作兔子在胡萝卜旁边晃动
heading = heading + (vector_to_mouse*.6)
position += heading*time_passed_seconds
可运行程序为:
第四篇pygame的学习就到此结束啦!