Search code examples
pythonpixel-perfect

Pygame pixel perfect collision code not working


I'm importing pixelperfect and using one of its functions called check_collision(object1, object2) here's the website I got it from http://www.pygame.org/wiki/FastPixelPerfect when I use the function it always returns false, and I have no idea why. If anyone could help me or have a better way to do pixelperfect collision I would be grateful.

It's always returning false that's the problem.

Here's the code:

import pygame, pixelperfect
from pygame.locals import *
from pixelperfect import *

screen = pygame.display.set_mode([640, 480])
screen.fill([255,255,255])
pygame.display.flip()

class Ball(object):
    def __init__(self, picture, speed, loc):
        self.image = pygame.image.load(picture)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = loc
        self.speed = speed

    def move(self):
        self.rect = self.rect.move(self.speed)

        if self.rect.left < 0 or self.rect.right > screen.get_width():
            self.speed[0] = - self.speed[0]
        elif self.rect.top < 0 or self.rect.bottom > screen.get_height():
            self.speed[1] = - self.speed[1]

ball = Ball("beach_ball.png", [5,5], [0,0])
ball.rect.center = [80, 50]
ball2 = Ball("beach_ball.png", [-5,-5], [200, 200])
ball2.rect.center = [100, 200]
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill([255,255,255])
    ball.move()
    ball2.move()
    if check_collision(ball, ball2):
        print 'hit'

    screen.blit(ball.image, ball.rect)
    screen.blit(ball2.image, ball2.rect)
    pygame.display.flip()
    clock.tick(30)
pygame.quit()

Solution

  • From the page you provided:

    All objects must have a 'rect' attribute and a 'hitmask' attribute.

    You only implemented rect. It uses the hitmap to check if there is a collision and since you don't provide one it returns false.

    Edit: Try using get_full_hitmask(image, rect) to get a hitmask, and add it to the object.