How to detect collision of two objects in Pygame

Here in this tutorial, we will learn how to detect the collision of two objects using Pygame which is a widely used Python library for building games with a very good graphical user interface.

So to detect the collision we will be using the inbuilt Pygame function colliderect.

You can view how to create a basic Pygame screen on how to detect a mouse click

Creating objects sliding around the screen

import pygame

pygame.init()

screen = pygame.display.set_mode((500, 450))

x1, y1 = 200, 250
x2, y2 = 430, 70

while True:
    screen.fill((0, 0, 0))
    circle1 = pygame.draw.circle(screen, (249, 246, 238), (x1, y1), 35)
    circle2 = pygame.draw.circle(screen, (130, 202, 250), (x2, y2), 35)
    
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            pygame.quit()
            exit()

        if i.type == pygame.KEYDOWN:
            if i.key == pygame.K_LEFT:
                x1 -= 10
            if i.key == pygame.K_RIGHT:
                x1 += 10
            if i.key == pygame.K_UP:
                y1 -= 10
            if i.key == pygame.K_DOWN:
                y1 += 10

    pygame.display.update()

Here we have already defined a fixed place where the x and y coordinates of the circles will be at the start, other than that we have used some inbuilt pygame functions to simplify the task.

  • pygame.init: As there are a lot of pygame functions used in the code it is important to initialize all those functions.
  • screen.fill(color code): Used for filling the screen with the color of choice at every instance.
  • pygame.draw.circle: Used for making circles on the screen which will be moving around for collision to happen.
  • pygame.KEYDOWN: Used to check if any key on the keyboard is pressed
  • pygame.K_LEFT, RIGHT, UP, DOWN: This specifies which arrow keys are pressed at the moment and how it’s going to affect the moment of the circles.

Detecting collision

Now to check when the collision takes place we will use colliderect() function as follows:

if circle1.colliderect(circle2):
        pygame.draw.circle(screen,(188,28,252),(x1,y1),35)

By just adding this if statement in the while loop defined earlier we will be able to see when the figures collide by changing the color of the moving circle.

Thus we have implemented the collision of two objects.

Leave a Reply

Your email address will not be published.