最近比较忙,国庆正好有时间写了python版本的愤怒的小鸟,使用了物理引擎pymunk,图片资源是从github上下载的,实现了一个可玩的简单版本。
功能实现如下:
游戏实现代码的github链接 愤怒的小鸟
这边是csdn的下载链接 愤怒的小鸟
pymunk是一个2D的物理引擎, 它实际是封装了 c语言写的2D物理引擎Chipmunk,可以实现碰撞,旋转等物理运动。
安装pymunk,可以直接使用pip工具,安装最新的pymunk 5.5.0:
pip install pymunk
介绍下在pymunk中会使用到的四个基本的类:
将物理引擎相关的代码单独放在了一个文件 (source\component\physics.py)中,减少代码的耦合。
定义了一个Physics类,向外提供所有物理引擎相关的函数。
这篇文章只介绍physics.py 中pymunk相关的代码。
reset 函数初始化了 空间类(pm.Space), 设置了两个参数
setup_lines函数设置了一条直线,作为地面。
Segment类创建了一条从点a 到 点b的直线。
class pymunk.Segment(body, a, b, radius)
Bases: pymunk.shapes.Shape
A line segment shape between two point. Meant mainly as a static shape.
import pymunk as pm
class Physics():
def __init__(self):
self.reset()
def reset(self, level=None):
self.level = level
# init space: set gravity and dt
self.space = pm.Space()
self.space.gravity = (0.0, -700.0)
self.dt = 0.002
self.birds = []
self.pigs = []
self.blocks = []
self.path_timer = 0
self.check_collide = False
self.setup_lines()
self.setup_collision_handler()
def setup_lines(self):
# Static Ground
x, y = to_pymunk(c.SCREEN_WIDTH, c.GROUND_HEIGHT)
static_body = pm.Body(body_type=pm.Body.STATIC)
static_lines = [pm.Segment(static_body, (0.0, y), (x, y), 0.0)]
for line in static_lines:
line.elasticity = 0.95
line.friction = 1
line.collision_type = COLLISION_LINE
self.space.add(static_lines)
self.static_lines = static_lines
setup_collision_handler 函数用来设置在两种类型的物体在碰撞发生时,可以由用户使用的回调函数。
add_collision_handler 函数添加两种类型物体a和b碰撞时会调用的handler。比如小猪和小鸟这两种类型物体的注册函数就是:add_collision_handler(COLLISION_PIG, COLLISION_BIRD)
add_collision_handler(collision_type_a, collision_type_b)
Return the CollisionHandler for collisions between objects of type collision_type_a and collision_type_b.
我们这里只用到了 post_solve 回调函数,在两个物体碰撞结束后,获取碰撞冲击力(collision impulse)。
post_solve
Two shapes are touching and their collision response has been processed.
func(arbiter, space, data)
You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See Arbiter for more info.
比如handle_pig_collide函数在小猪和障碍物碰撞后,会根据冲击力的大小来相应减去小猪的生命。
COLLISION_BIRD = 1
COLLISION_PIG = 2
COLLISION_BLOCK = 3
COLLISION_LINE = 4
def setup_collision_handler(self):
def post_solve_bird_line(arbiter, space, data):
if self.check_collide:
bird_shape = arbiter.shapes[0]
my_phy.handle_bird_collide(bird_shape, True)
def post_solve_pig_bird(arbiter, space, data):
if self.check_collide:
pig_shape = arbiter.shapes[0]
my_phy.handle_pig_collide(pig_shape, MAX_IMPULSE)
def post_solve_pig_line(arbiter, space, data):
if self.check_collide:
pig_shape = arbiter.shapes[0]
my_phy.handle_pig_collide(pig_shape, arbiter.total_impulse.length, True)
def post_solve_pig_block(arbiter, space, data):
if self.check_collide:
if arbiter.total_impulse.length > MIN_DAMAGE_IMPULSE:
pig_shape = arbiter.shapes[0]
my_phy.handle_pig_collide(pig_shape, arbiter.total_impulse.length)
def post_solve_block_bird(arbiter, space, data):
if self.check_collide:
block_shape, bird_shape = arbiter.shapes
my_phy.handle_bird_collide(bird_shape)
if arbiter.total_impulse.length > 1100:
my_phy.handle_block_collide(block_shape, arbiter.total_impulse.length)
self.space.add_collision_handler(
COLLISION_BIRD, COLLISION_LINE).post_solve = post_solve_bird_line
self.space.add_collision_handler(
COLLISION_PIG, COLLISION_BIRD).post_solve = post_solve_pig_bird
self.space.add_collision_handler(
COLLISION_PIG, COLLISION_LINE).post_solve = post_solve_pig_line
self.space.add_collision_handler(
COLLISION_PIG, COLLISION_BLOCK).post_solve = post_solve_pig_block
self.space.add_collision_handler(
COLLISION_BLOCK, COLLISION_BIRD).post_solve = post_solve_block_bird
def handle_pig_collide(self, pig_shape, impulse, is_ground=False):
for pig in self.pigs:
if pig_shape == pig.phy.shape:
if is_ground:
pig.phy.body.velocity = pig.phy.body.velocity * 0.8
else:
damage = impulse // MIN_DAMAGE_IMPULSE
pig.set_damage(damage)
# must init as a global parameter to use in the post_solve handler
my_phy = Physics()
创建物体一般有下面五个步骤
moment_for_circle 函数根据质量(mass), 圆的半径 来计算出刚体的转动惯量(Moment Of Inertia),惯量就像刚体的旋转质量。
pymunk.moment_for_circle(mass, inner_radius, outer_radius, offset=(0, 0))
Calculate the moment of inertia for a hollow circle
inner_radius and outer_radius are the inner and outer diameters. (A solid circle has an inner diameter of 0)
根据质量和转动惯量来创建一个刚体(pymunk.Body)。
class pymunk.Body(mass=0, moment=0, body_type=)
根据刚体,和形状类型创建一个碰撞形状,比如圆形就是 pymunk.Circle。
class pymunk.Circle(body, radius, offset=(0, 0))
Bases: pymunk.shapes.Shape
A circle shape defined by a radius
设置形状的一些属性
摩擦系数(friction)
Friction coefficient.
Pymunk uses the Coulomb friction model, a value of 0.0 is frictionless.
A value over 1.0 is perfectly fine.
弹力 (elasticity)
Elasticity of the shape.
A value of 0.0 gives no bounce, while a value of 1.0 will give a ‘perfect’ bounce.
最后将这个刚体和碰撞形状都添加到空间中。
pymunk.Space.add(*objs)
Add one or many shapes, bodies or joints to the space
class PhyPig():
def __init__(self, x, y, radius, space):
mass = 5
inertia = pm.moment_for_circle(mass, 0, radius, (0, 0))
body = pm.Body(mass, inertia)
body.position = x, y
shape = pm.Circle(body, radius, (0, 0))
shape.elasticity = 0.95
shape.friction = 1
shape.collision_type = COLLISION_PIG
space.add(body, shape)
self.body = body
self.shape = shape
PhyPig 类的初始化函数创建了一个小猪物体,参数有物体的位置(x,y), 可以将小猪作为一个圆形物体,所以参数有圆的半径(radius), 参数space就是我们上面创建的空间类。
update函数是更新函数,代码只显示了小猪相关的代码。
step 函数的参数dt值就是上面设置的时间段值,表示这次调用 该空间经过了多少时间,pymunk 根据这个时间值更新空间中的所有物体的状态(比如速度,位置等)。按照pymunk 文档的说明,将dt值设小一点,每次调用多次会使得模拟更稳定和精确,所以这里每次调用5次step函数。
pymunk.Space.step(dt)
Update the space for the given time step.
遍历所有的小猪:
def to_pygame(p):
"""Convert position of pymunk to position of pygame"""
return int(p.x), int(-p.y+600)
def update(self, game_info, level, mouse_pressed):
pigs_to_remove = []
#From pymunk doc:Performing multiple calls with a smaller dt
# creates a more stable and accurate simulation
#So make five updates per frame for better stability
for x in range(5):
self.space.step(self.dt)
...
for pig in self.pigs:
pig.update(game_info)
if pig.phy.body.position.y < 0 or pig.life <= 0:
pigs_to_remove.append(pig)
poly = pig.phy.shape
p = to_pygame(poly.body.position)
x, y = p
w, h = pig.image.get_size()
# change to [left, top] position of pygame
x -= w * 0.5
y -= h * 0.5
angle_degree = math.degrees(poly.body.angle)
pig.update_position(x, y, angle_degree)
for pig in pigs_to_remove:
self.space.remove(pig.phy.shape, pig.phy.shape.body)
self.pigs.remove(pig)
level.update_score(c.PIG_SCORE)
...
python3.7 + pygame1.9 + pymunk 5.5.0