Search code examples
python-3.xpygamespritecollision-detection

Pygame is always sensing collision between two rect objects


As soon as I run the code, Pygame returns that Bird and Pipe are colliding, even when they are obviously not.

I have tried using the colliderect function and added a get_rect to each of the pictures that I am rendering onto the screen

code:

import pygame
from random import randint
pygame.init()

screen = pygame.display.set_mode((500, 750))
gravity = 0


class Pipe(pygame.sprite.Sprite):
    def __init__(self, x_change, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.x_change = x_change
        self.x = x
        self.y = y
        self.pic1 = pygame.image.load('file/path.png')
        self.pic1 = pygame.transform.scale(self.pic1, (28*2, 600*2)).convert_alpha()
        self.pic2 = pygame.image.load('file/path.png')
        self.pic2 = pygame.transform.scale(self.pic2, (28*2, 600*2)).convert_alpha()
        self.rect1 = self.pic1.get_rect()
        self.rect2 = self.pic2.get_rect()

    def collision(self, sprite):
        return self.rect1.colliderect(sprite) or self.rect2.colliderect(sprite)


class Bird(pygame.sprite.Sprite):
    def __init__(self, bird_width, bird_height, y_change, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.pic = pygame.image.load('file/path.png').convert_alpha()
        self.pic = pygame.transform.scale(self.pic, (bird_width, bird_height))
        self.rect = self.pic.get_rect()
        self.bird_width = bird_width
        self.bird_height = bird_height
        self.y_change = y_change
        self.x = x
        self.y = y
        self.velocity = 0
        self.term_velocity = 15


bird = Bird(40, 30, 5, 0, 0)
pipe = Pipe(3, 500, randint(30, 650))

while True:
    if pipe.collision(bird.pic.get_rect()):
        print('collision')
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    gravity += 0.01
    pygame.display.flip()
    pygame.time.Clock().tick(60)

EDIT: After following the advice from Hoog below, the position of both the rects are 0, 0. How would I change the position of the get_rect()?


Solution

  • I actually answered my own question. Where I say get_rect(), the position of the rect is (0, 0). I figured this out thanks to the comments above. I needed to say: self.rect = self.pic.get_rect(center=(self.x, self.y)) Now, I have it working.