使用PyGame进行碰撞检测

时间:2015-05-31 16:41:38

标签: python pygame collision-detection game-physics

我用PyGame制作了一个使用Python的2d平台游戏。这一切都很顺利,但我遇到了碰撞检测的许多问题。他们在这里:

  1. 您无法浏览具有确切空间的对象
  2. 你可以穿过天花板(非常奇怪)
  3. 我的代码非常大,我认为,因为它涉及多个类,我应该将它发布在GitHub上,所以这里是我的存储库的链接:https://github.com/pta2002/SuperBros

    但仅供参考,这是我的colliion检测方法:

    def detectCollisions(self, x1, y1, w1, h1, x2, y2, w2, h2):
    
        if x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2:
            return 1
    
        elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2:
            return 2
    
        elif x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
            return 3
    
        elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
            return 4
    
        else:
            return 0
    

    这是我的更新方法:

    def update(self, gravity, block_list):
        if self.velocity < 0:
            self.falling = True
    
        collision = 0
        blockX, blockY = 0, 0
        self.canMoveRight = True
        self.canMoveLeft = True
    
        for block in block_list:
            collision = self.detectCollisions(self.x, self.y, self.width, self.height,
             block.x, block.y, block.width, block.height)
    
            if not collision == 0:
                blockX = block.x
                blockY = block.y
                break
    
        if not collision == 0:
            if self.falling:
                self.falling = False
                self.onGround = True
                self.velocity = 0
                self.y = block.y - self.height
            else:
                if collision == 2:
                    self.canMoveRight = False
    
                if collision == 1:
                    self.canMoveLeft = False
        else:
            self.falling = True
            self.onGround = False
    
        if not self.onGround:
            self.velocity += gravity
    
        self.y -= self.velocity
        if (self.canMoveRight and self.xvel > 0) or (self.canMoveLeft and self.xvel < 0):
            self.x += self.xvel
    
        if self.jumping:
            if self.onGround:
                self.velocity = 8
                self.onGround = False
    
        if self.cur_image >= self.num_images - 1:
            self.cur_image = 0
        else:
            self.cur_image += 1
    

1 个答案:

答案 0 :(得分:0)

熟悉pygame.Rect,如果使用精灵,它几乎解决了碰撞检测的所有问题。 (https://www.pygame.org/docs/ref/rect.html) 你像这样碰撞它们(方法如果碰撞则返回True):

rect.colliderect(otherrect)