pygame冲突的问题



我一直在尝试进行水平和垂直碰撞,但我在水平碰撞方面遇到了问题。我使用了碰撞检查作为一种方法来验证玩家触摸了多少瓷砖,因为这是我能想到的水平和垂直的唯一区别。但是,我的玩家从来没有接触过2个瓦片,因为出于某种原因,垂直碰撞总是排在第一位,而我的玩家只是被罚出场,而不是与2个瓦片碰撞。

collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.y>0:
player.rect.bottom=tile.rect.top
player.direction.y=0
elif player.direction.y<0:
player.rect.top=tile.rect.bottom
player.direction.y=0.1

您必须分别处理水平和垂直移动和碰撞:

  • 在x方向移动玩家
  • 检测碰撞并限制玩家在X方向上的移动
  • 沿y方向移动播放器
  • 检测碰撞并限制玩家在y方向上的移动

您可以根据移动轴而不是移动本身,尝试仅分离碰撞检测和玩家位置限制,但这可能无法完全解决您的问题。如果你总是轻微摔倒,即使你站在瓷砖上,这也会是一个问题,因此水平碰撞检测将始终检测到与你站在的瓷砖的碰撞。

你的代码应该是这样的:

# do the horizontal movement here, something like:
# player.rect.x += player.direction.x
collide_x = False
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.x > 0:
player.rect.right = tile.rect.left
collide_x = True
elif player.direction.x < 0:
player.rect.left = tile.rect.right
collide_x = True
if collide_x:
player.direction.x = 0
# do the vertical movement here, something like:
# player.rect.y += player.direction.y
collide_y = False
collisioncheck=pygame.sprite.groupcollide(self.player,self.tiles,False,False)
for tile in self.tiles.sprites():
if player.rect.colliderect(tile.rect):
if player.direction.y > 0:
player.rect.bottom = tile.rect.top
collide_y = True
elif player.direction.y <= 0:
player.rect.top = tile.rect.bottom
collide_y = True
if collide_y:
player.direction.y = 0

最新更新