I am trying to understand the way that pixelperfect collisions works, I have made a program using two circles(images) bouncing around in the pygame window. This is the script:
it uses pygame and this script:
The problem is that it always returns "None"(whic h makes the balls running through eachothers), the only thing I have determinated is that it should be something with the obj.hitmask and the obj.blank
Hope you understand the problem:/
i would be very grateful to the one/ones who can help
please help
Code:
import pygame, importedfunctions, random
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([640,480])
class BallClass(pygame.sprite.Sprite):
def __init__(self, x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ball.png")
self.rect = self.image.get_rect()
self.rect.left = x
self.rect.top = y
self.speed = [6,6]
def move(self):
global ballgroup
x = self.rect.left
self.rect.left += self.speed[0]
y = self.rect.top
self.rect.top += self.speed[1]
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] *= -1
self.rect.left = x
if self.rect.top < 0 or self.rect.bottom > screen.get_height():
self.rect.top = y
self.speed[1] *= -1
for i in ballgroup:
z = importedfunctions.PixelPerfectCollision(self, i)
if z == True:
self.speed[0] *= -1
self.speed[1] *= -1
print "collide!"
else: print z
ballgroup = pygame.sprite.Group()
ball1 = BallClass(20,20)
ballgroup.add(ball1)
ball2 = BallClass(200,20)
ballgroup.add(ball2)
def blitting():
global ballgroup, screen
screen.fill([0,0,0])
for i in ballgroup:
i.move()
for i in ballgroup:
screen.blit(i.image,i.rect)
stop = False
def while_loop():
while stop == False:
clock.tick(30)
blitting()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
while_loop()
Code:
def PixelPerfectCollision(obj1, obj2):
"""
If the function finds a collision, it will return True;
if not, it will return False. If one of the objects is
not the intended type, the function instead returns None.
"""
try:
#create attributes
rect1, mask1, blank1 = obj1.rect, obj1.hitmask, obj1.blank
rect2, mask2, blank2 = obj2.rect, obj2.hitmask, obj2.blank
#initial examination
if rect1.colliderect(rect2) is False:
return False
except AttributeError:
return None
#get the overlapping area
clip = rect1.clip(rect2)
#find where clip's top-left point is in both rectangles
x1 = clip.left - rect1.left
y1 = clip.top - rect1.top
x2 = clip.left - rect2.left
y2 = clip.top - rect2.top
#cycle through clip's area of the hitmasks
for x in range(clip.width):
for y in range(clip.height):
#returns True if neither pixel is blank
if mask1[x1+x][y1+y] is not blank1 and \
mask2[x2+x][y2+y] is not blank2:
return True
#if there was neither collision nor error
return False
Hope you understand the problem:/
i would be very grateful to the one/ones who can help
please help
Comment