我正在用 python 和 pygame 开发一个平台游戏。完整代码可以在“https://github.com/C-Kimber/FBLA_Game“。我遇到的问题是玩家精灵和墙壁精灵之间的碰撞,特别是角落。当玩家按下 x 移动键并跳跃时,玩家要么不动,要么被卡住。这是碰撞样本:
def wallCollisions(self):
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
if self.rect.bottom >= block.rect.top and self.rect.bottom <= block.rect.top + 15: # Moving down; Hit the top side of the wall
if self.rect.right > block.rect.left:
self.rect.bottom = block.rect.top
self.yvel = 0
self.onGround = True
self.jumps = 1
elif self.rect.top <= block.rect.bottom and self.rect.top >= block.rect.bottom - 15: # Moving up; Hit the bottom side of the wall
self.rect.top = block.rect.bottom
self.yvel = 0
if self.rect.right >= block.rect.left and self.rect.right <= block.rect.left + 15: # Moving right; Hit the left side of the wall
if self.rect.bottom > block.rect.top+15:
self.rect.right = block.rect.left#+1
self.xvel = 0
elif self.rect.left <= block.rect.right and self.rect.left >= block.rect.right - 15: # Moving left; Hit the right side of the wall
self.rect.left = block.rect.right#-1
self.xvel = 0 = block.rect.right#-1
self.xvel = 0
I've included images on what is happening and what I want.
我尝试过其他方法,例如使用速度作为碰撞的确定因素,但这是迄今为止效果最好的方法。如果您能提供解决方案,我们将不胜感激。
感谢懒惰用户!他所提出的问题给了我一些急需的清晰度。我花了一点时间,但我实现了它。我为碰撞创建了一个函数。
def wallColl(self, xvel, yvel, colliders):
for collider in colliders:
if pygame.sprite.collide_rect(self, collider):
if xvel > 0:
self.rect.right = collider.rect.left
self.xvel = 0
if xvel < 0:
self.rect.left = collider.rect.right
self.xvel = 0
if yvel < 0:
self.rect.bottom = collider.rect.top
self.onGround = True
self.jumps = 3
self.yvel = 0
if yvel > 0:
self.yvel = 0
self.rect.top = collider.rect.bottom
然后我在更新函数中调用它们。
def update(self):
self.rect.x += self.xvel
# self.walls is an array of sprites.
self.wallColl(self.xvel, 0, self.walls)
self.rect.y -= self.yvel
self.onGround = False
self.wallColl(0, self.yvel, self.walls)
self.wallCollisions()
if self.otherplayers != None:
self.playerCollisions()
# Gravity
if self.onGround == False:
self.yvel-=.0066*self.mass
self.boundries(highbound, lowbound, leftbound, rightbound)
self.down = False
我的游戏中的实际使用使可用性近乎完美。虽然不是 100%,但这并不是一个完美的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)