pythonpygamecollision-detection

Pygame Collision Detection Bugged


I'm coding my first game on Pygame. I'm trying to make the collision detection but it only works sometimes.

I tried to use pygame.sprite.groupcollide but I'm currently using pygame.sprite.collide_rect

This is my collision code:

for event in pygame.event.get():
    collision = pygame.sprite.collide_rect(Dog, spikeUp0) or pygame.sprite.collide_rect(Dog, spikeUp1) or pygame.sprite.collide_rect(Dog, spikeDown0) or pygame.sprite.collide_rect(Dog, spikeDown1)
    if collision:
        Game = False
        gameOver()

I expect that when I touch the spikes, starts the gameOver function, but it only works sometimes.


Solution

  • You've to do the collision test in the main loop rather then the event loop. The event loop is executed only when an event occurs, this causes that it "only sometimes works". The main loop is executed continuously.

    e.g.

    # main application loop 
    while run:
    
        # event loop
        for event in pygame.event.get():
    
            # [...] event handling    
    
    
        # collison test
        collision = pygame.sprite.collide_rect(Dog, spikeUp0) or pygame.sprite.collide_rect(Dog, spikeUp1) or pygame.sprite.collide_rect(Dog, spikeDown0) or pygame.sprite.collide_rect(Dog, spikeDown1)
        if collision:
            Game = False
            gameOver()