Search code examples
pythonpython-3.xpygamegame-physics

Pygame platformer collision detection not working


I am trying to implement collision detection to my platformer game. When i try to run the game i just fall through the platform as opposed to stopping when the player hits it. Any help or suggestions would be greatly appreciated. My full code can be found here

    def collision_detect(self,x1,y1,platform):
    #Stops the player from falling once they hit the platform by setting falling to false
    if self.x > platform.x and self.x < platform.x2:
        if self.y == platform.y:
             self.yVel += 0 

Solution

  • There are a few mistakes, in logic and in implementation.

    • In your collision_detect you say that you change the state of falling to false but you never do it. Also, you set falling to true right before checking it. But see my other points, first.

    • The player should not have a state "falling" or "not falling". The gravity is always there, so the player is always falling. If there's a platform to block it, velocity drops to 0, and that's it. Just like you're actually falling but there's the floor stopping you.

    • You should not check that self.y == platform.y, because if you increase the y coordinate by 2 or 3, you might "skip" the exact coordinate, so what you actually want is self.y >= platform.y.

    • You can completely remove the gravity method and only use the collision_detect method.

    Something like this:

    def collision_detect(self, platform):
        if self.x > platform.x and self.x < platform.x2:
            if self.y >= platform.y:
                self.yVel = 0
            else:
                self.yVel = 5
    

    Try it with something like self.collision_detect(platform(0, 500, 800, 20)) in your do function.