Skip to content Skip to sidebar Skip to footer

My Collision Detection Is Not Working Properly

I was programming a game in python using the pygame and math modules. I wrote these codes for doing a collision detection (I made 5 obstacles with which I want my player to collide

Solution 1:

Actually, you are just checking if the player is touching an obstacle, but you will miss the collision if the player intersects the obstacle. You have to evaluate if distance <= 27 rather than distance == 27. Furthermore it is completely sufficient to implement 1 function for the collision test.

def collide(x1, y1, x2, y2):
    distance = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
    if distance <= 27:
        return True
    else:
        return False

The function can be further simplified:

def collide(x1, y1, x2, y2):
    distance = math.hypot(x1 - x2, y1 - y2)
    return distance <= 27

Use a loop to do the collision test:

obstacles = [(binX, binY), (snowX, snowY), (glacierX, glacierY), (boardX, boardY), (iceX, iceY)]

for x, y in obstacles:
    collision = collide(x, y, playerX, playerY)
    if collision:
        print("You have collided!")

Solution 2:

Right now you only collide if the distance is exactly 27. If you assume spheres, you can still consider them "colliding" if they are less than 27 pixels appart.

So replace all your distances with if distance <= 27: Note the less than or equals.

Another thing to note is that calculating square roots is very slow. It's much faster to check if distance_squared <= 27 * 27 then to check math.pow(distance_squared, 0.5) <= 27.


Post a Comment for "My Collision Detection Is Not Working Properly"