首页 > 解决方案 > Pygame 碰撞处理

问题描述

我用 pygame 制作了一个 2D 平台游戏。我正在努力弄清楚如何确定物体移动的方向。

例如:假设玩家从上面来,因为他的 y 速度大于零,那么问题是他的引力一直在作用于他;这意味着如果他来自左侧,他的 y 速度大于零(因此即使我希望触发左侧 if 语句,也会触发这个 if 语句)。

源代码如下:`

if self.hits:
    for platform in self.hits:

        if self.player.vel.y > 0:
            self.player.rect.y = platform.rect.top
            self.player.vel.y = 0

        if self.player.vel.y < 0:
            self.player.rect.top = platform.rect.bottom
            self.player.vel.y = 0

        if self.player.vel.x > 0:
            self.player.rect.right = platform.rect.left

        if self.player.vel.y < 0:
            self.player.rect.left = platform.rect.right

这就是为什么我为每个四个方向的识别设置了一些限制:`

if self.hits:
   for platform in self.hits:

       if self.player.rect.bottom >= (platform.rect.top) and self.player.rect.bottom <= (platform.rect.top + 16)\
       and (self.player.rect.centerx + 13) >= platform.rect.left and (self.player.rect.centerx - 13) <= platform.rect.right:
               self.player.pos_bottom.y = platform.rect.top
               self.player.vel.y = 0

       elif self.player.rect.top <= (platform.rect.bottom) and self.player.rect.top >= (platform.rect.bottom - 16)\
       and (self.player.rect.centerx + 13) >= platform.rect.left and (self.player.rect.centerx - 13) <= platform.rect.right:
               self.player.rect.top = platform.rect.bottom
               self.player.vel.y = 0

       elif self.player.rect.right >= (platform.rect.left) and self.player.rect.right <= (platform.rect.right + 10) and self.player.vel.x >= 0\
       and self.player.rect.centery >= platform.rect.top and self.player.rect.centery <= platform.rect.bottom:
           self.player.rect.right = platform.rect.left
           self.player.vel.x = 0

       elif self.player.rect.left <= (platform.rect.right) and self.player.rect.left >= (platform.rect.right - 10) and self.player.vel.x <= 0\
       and self.player.rect.centery >= platform.rect.top and self.player.rect.centery <= platform.rect.bottom:
           self.player.rect.left = platform.rect.right
           self.player.vel.x = 0`

这段代码限制了玩家方向被识别的区域,但也带来了很多错误,也很丑陋。

标签: pythonpygame2dcollision

解决方案


推荐阅读