Search code examples
pythonpython-3.xpygamecollision-detectionoverlap

How to collide two images in Pygame module


I’m new to programming and know the basics of Python and wanted to ask how I can perform an action if two images overlap a little bit and then a specific button is pressed in pygame. The game looks like following:

import pygame
import random

pygame.init()
window = pygame.display.set_mode((1000, 600))
caption = pygame.display.set_caption(
    'Test your reaction speed. Shoot the target game!')  # sets a caption for the window
game_running = True  # this is the gameloop so the window stays open

PlayerImg = pygame.image.load('F:\PythonPortable\oscn.png')
PlayerX = 370
PlayerY = 420
PlayerX_change = 0
PlayerY_change = 0


def player():
    window.blit(PlayerImg, (PlayerX, PlayerY))


aim_sight = pygame.image.load('F:\PythonPortable\ktarget.png')
aim_sightX = 460
aim_sightY = 300
aim_sight_changeX = 0
aim_sight_changeY = 0


def aim_sight_function(x, y):
    window.blit(aim_sight, (x, y))


targetedImg = pygame.image.load('F:\PythonPortable\ktargetedperson.png')
targetedX = random.randint(0, 872)
targetedY = random.randint(0, 200)


def random_target():
    window.blit(targetedImg, (targetedX, targetedY))


while game_running:
    window.fill((255, 255, 255))
    random_target()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                aim_sight_changeX = -2
                PlayerX_change = -2
            elif event.key == pygame.K_RIGHT:
                aim_sight_changeX = 2
                PlayerX_change = 2
            elif event.key == pygame.K_UP:
                aim_sight_changeY = -2
                PlayerY_change = -2
            elif event.key == pygame.K_DOWN:
                aim_sight_changeY = 2
                PlayerY_change = 2
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                aim_sight_changeX = 0
                PlayerX_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                aim_sight_changeY = 0
                PlayerY_change = 0

    aim_sightX += aim_sight_changeX
    if aim_sightX <= 46.5:
        aim_sight_changeX = 0
    elif aim_sightX >= 936:
        aim_sight_changeX = 0
    aim_sightY += aim_sight_changeY
    if aim_sightY <= 0:
        aim_sight_changeY = 0
    elif aim_sightY >= 400:
        aim_sight_changeY = 0

    PlayerX += PlayerX_change
    if PlayerX <= -50:
        PlayerX_change = 0
    elif PlayerX >= 850:
        PlayerX_change = 0
    player()
    aim_sight_function(aim_sightX, aim_sightY)
    pygame.display.update()

I would like to know how a do what I want. I thought maybe:

if event.type == pygame.K_SPACE and targetedX == targetedX in range(aim_sightX - 100, aim_sightY + 100) or targetedY == targetedY in range (aim_sightY - 100, aim_sightY + 100):
...

It seems as though none of the tutorials I watched cover this topic and would like to recieve recommendations for tutorials that cover this problem or a direct answer.


Solution

  • I recommend to use a pygame.Rect objects and colliderect() to find a collision between two Surface objects. pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. The position of the rectangle can be specified by a keyword argument:

    PlayerImg_rect   = PlayerImg.get_rect(topleft = (PlayerX, PlayerY))
    targetedImg_rect = targetedImg .get_rect(topleft = (targetedX, targetedX))
    
    if PlayerImg_rect.colliderect(targetedImg_rect):
        print("hit")