0

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()
  • Your `Ball` class doesn't have a `hitmask` attribute, so `check_collision` raises an AttributeError on its first line. (I'm posting this as a comment and not an answer because I don't know if fixing this will solve the problem entirely, or if there are several other obscacles that need to be overcome, or what) – Kevin Mar 01 '16 at 16:14

1 Answers1

3

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.

Jan
  • 1,504
  • 10
  • 15
  • Could you give me an example please, I'm quite new to python and pygame. Thank you for the Quick answer. – Mr Bengtgöran Mar 01 '16 at 17:17
  • 1
    I don't have pixelperfect installed, only pygame, but try the following: Add `self.hitmask = get_full_hitmask(self.image,self.rect)` to your ball class AFTER self.speed – Jan Mar 01 '16 at 17:22
  • @MrBengtgöran Don't forget to mark any answer as a "accepted answer" if it solves your problem. Thank you in advance and welcome to SO. – Torxed Mar 01 '16 at 17:28