Search code examples
pythonpygamecollision-detection

Find distance between objects in python - Not working


I am currently working on a simple flappy bird-ish game on Python. For some reason, the collision code isn't working when the pipe and bird touch.

def collision():
    global distanceDown, distanceUp
    distanceUp = math.sqrt(math.pow(pipeUpX - birdX, 2) + math.pow(pipeUpY - birdY, 2))  # distance formula
    distanceDown = math.sqrt(math.pow(pipeDownX - birdX, 2) + math.pow(pipeDownX - birdY, 2))

    if distanceUp <= 20 or distanceDown <= 20:
        return True
    else:
        return False

I've called the function in the main game loop and asked python to end the game if true, but the bird just passes through the pipe.FYI, I haven't used OOP and classes.Here are the values..

pipeWidth = 50
pipeHeight = 130
pipeUpX = 800
pipeUpY = 0
pipeDownY = screenY - pipeHeight
pipeDownX = 900
pipeX_change = 1

Also, I'm quite new to python and programming as a whole, so please answer in easy to understand code. Thank You :)


Solution

  • The code does not verify the distance to the pipe. The code verifies the distance to the start and the end of the pipe. That is something different.

    Since your objects just rectangles, I recommend to use pygame.Rect objeccts and the colliderect method. For instance some pseudo code:

    def collision():  
        pipeRect = pygame.Rect(pipeLeft, pipeTop, pipeWidth, pipeHeight) 
        birdRect = pygame.Rect(birdLeft, birdTop, birdWidth, birdHeight) 
        return pipeRect.colliderect(birdRect)
    

    For the collision of "images", I recommend to use pygame.sprite.Sprite / pygame.sprite.collide_mask() respectively pygame.mask.Mask / pygame.mask.Mask.overlap().

    See further:
    Collision between masks in pygame
    How can I made a collision mask?
    Pygame mask collision