Jashan
Jashan

Reputation: 13

Pygame collision detection issue

I am making a game with pygame where you have to dodge falling objects. I am having trouble with the collision detection, as when the obstacle touches the player, it just passes through to the bottom. Here is my code.

pygame.K_LEFT:
        p_x_change = 0

screen.fill(WHITE)
pygame.draw.rect(screen,BLUE,(p_x,p_y, 60, 60))
pygame.draw.rect(screen,RED,(e_x,e_y,100,100))
p_x += p_x_change
e_y += e_ychange
if e_y > display_height:
    e_y = 0
    e_x = random.randint(1,display_width)
 #Collision detection below

elif e_y == p_y - 90 and e_x == p_x :
    done = True
clock.tick(60)
pygame.display.update()

Could you tell me what is wrong with my code?

Upvotes: 1

Views: 264

Answers (1)

skrx
skrx

Reputation: 20438

I suggest to create two pygame.Rects, one for the player and one for the enemy. Then move the enemy by incrementing the y attribute of the rect and use the colliderect method to see if the two rects collide.

import random
import pygame


pygame.init()
screen = pygame.display.set_mode((640, 480))
display_width, display_height = screen.get_size()
clock = pygame.time.Clock()
BG_COLOR = pygame.Color('gray12')
BLUE = pygame.Color('dodgerblue1')
RED = pygame.Color('firebrick1')
# Create two rects (x, y, width, height).
player = pygame.Rect(200, 400, 60, 60)
enemy = pygame.Rect(200, 10, 100, 100)
e_ychange = 2

done = False
while not done:
    # Event handling.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        player.x -= 5
    elif keys[pygame.K_d]:
        player.x += 5

    # Game logic.
    enemy.y += e_ychange  # Move the enemy.
    if enemy.y > display_height:
        enemy.y = 0
        enemy.x = random.randint(1, display_width)
    # Use the colliderect method for the collision detection.
    elif player.colliderect(enemy):
        print('collision')

    # Drawing.
    screen.fill(BG_COLOR)
    pygame.draw.rect(screen, BLUE, player)
    pygame.draw.rect(screen, RED, enemy)
    pygame.display.flip()
    clock.tick(30)

pygame.quit()

Upvotes: 1

Related Questions