到目前为止,我从一个平坦的平台开始,我的角色在上面。
我已经实现了重力和跳跃功能。
因此,重力概念的工作原理如下,继续向下下降,直到玩家与他下方的物体相撞。
所以,当我在我的英雄下有一个平坦的平台时,但当我想实现一个屋顶时,这是有效的。所以在我的播放器顶部和下方都有一个平坦的平台。
我的重力函数一直在下降。我的地形都在pygame.Rect列表中。
我的重力功能遍历我所有的地形,并检查玩家是否在地板物体上方,如果是这样,请继续下降。
我注意到的问题是,由于我的角色上方有对象,它一直在下降。我似乎无法找到一种方法来忽略我角色上方的瓷砖,而只关注玩家下方的瓷砖并检查串通。
一旦我弄清楚了这个勾结问题,我相信我可以在跳起来检查与屋顶的碰撞并左右移动时弄清楚它。
感谢帮助。
编辑:地形是"我的对象"图块的列表。现在地形只有 2 个对象
#this is not correct way initialize just displaying my 2 object's rect
terrain = [<rect(400, 355, 50, 49)>,<rect(500, 198, 50, 49)>]
def GRAVITY(self, terrain):
'''----------break is cutting of parsing the rest of the terrain.
----------Need to search through each terrain. Keep falling until collide with an object under the hero ONLY.
'''
for i in range(len(terrain)):
print i
#stop falling when colliding with object
if terrain[i].top > self.rect.bottom:
print 'above tile while falling'
self.y += JUMPRATE
break
#continue falling if not standing on the object. Also catch when walking of an object then fall.
elif terrain[i].top <= self.rect.bottom and not self.rect.colliderect(terrain[i]):
print 'whoops missed tile'
self.y +=JUMPRATE
break
else:
print 'on tile'
self.y = self.y
break
这是玩家跳跃时调用的函数。
在您的代码中,每个子句中都有一个 break 语句,因此无论列表中有多少Rect
,循环都将始终运行一次。
您可以做的是使用 collided
标志,并且仅在发生碰撞时才中断。
def fall(self, terrain):
collided = False
for rect in terrain:
if self.rect.colliderect(rect):
collided = True
break
if not collided:
self.y += JUMPRATE
如果没有碰撞,角色就会倒下。 否则,它不会移动。 不过,您必须添加一些东西来处理它从侧面碰撞的情况。 此外,角色的脚会稍微穿过地板,因此一旦发生碰撞,您应该将角色的rect.bottom
设置为地形的top
。