Collision Detection in pygame using Python

In this module, we are going to discuss the collision detection between objects in pygame. This is helpful when we want to less health bar when hit with bullets or when we want to end the game if collided with walls etc. To implement this we require a hitbox in which our Collison characters are enclosed.

Detect Collision using colliderect() in pygame – Python

Here we are going to use colliderect() function whose functionality is to return True if a collision occurs between two rectangles else return False. It functions with pygame.Rect object. Here we will use movement keys like up arrow, down arrow, left arrow, right arrow for the movement of the rectangle.

The syntax for colliderect() is as follows

rect_obj.colliderect(rect_coll_obj)

Here rect_obj is one rectangular object and rect_coll_obj is another rectangular object which returns True if both the rectangle collide.

The following code describes the collision Detection

import pygame
import sys
pygame.init()
fps=30
fpsclock=pygame.time.Clock()
sur_obj=pygame.display.set_mode((400,300))
pygame.display.set_caption("Rectangle")
black=(0,0,0)
p1=10
p2=10
step=5
while True:
    sur_obj.fill((255,255,255))
    t=pygame.draw.rect(sur_obj,(0,0,255),(200,150,65,48))
    s=pygame.draw.rect(sur_obj, (0,255,0), (p1, p2,52,31))
    hitbox = (p1-5,p2-5,59,39)
    hitbox1=(195,145,73,55)
    z=pygame.draw.rect(sur_obj,(255,0,0),hitbox,2)
    z1=pygame.draw.rect(sur_obj,(255,0,0),hitbox1,2)
    for eve in pygame.event.get():
        if eve.type==pygame.QUIT:
            pygame.quit()
            sys.exit()
    key_input = pygame.key.get_pressed()   
    if key_input[pygame.K_LEFT]:
        p1 -= step
    elif key_input[pygame.K_UP]:
        p2 -= step
    elif key_input[pygame.K_RIGHT]:
        p1 += step
    elif key_input[pygame.K_DOWN]:
        p2 += step
    else:
        colliding=z1.colliderect(z)
    if colliding:
        sur_obj.fill((0,0,0))  
    pygame.display.update()
    fpsclock.tick(fps)

Output:

  • When we execute the above code we get like this

Collision Detection in pygame using Python

  • When the collision occurs we get the output as follows

Collision Detection in pygame using Python

  • When we move rectangle away from a collision using movement keys you get a normal screen as the beginning.

away from a collision using movement key

The above code gives the output as a screen with two rectangles with a hitbox. When the green rectangle hitbox collides with a blue rectangle hitbox the screen goes black indicate collision has occurred. That’s when we move rectangle from that collision you get the normal screen.

colliding=z1.colliderect(z)

Here, this condition checks the collision. I assigned this to an object which is helpful if making the screen blank when a collision has occurred.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *