[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Pixel Perfect collision suggestion.



V. Karthik Kumar wrote:
I happened to read the changes list a day ago. I saw the code, I thought that this change might help detect regular pp cols faster.

This version keeps checking pixels from the outer rectangle of the colliding area to the inner. It works considerably faster when objects are regular and convex, which is often the case.

This isn't a patch as such, I'd recommend people try it out and report the results and then decide.

Regards,
Karthik


------------------------------------------------------------------------

def pp_collide(obj1,obj2):
    """If the function finds a collision it will return True
    if not it will return False.
    """
    rect1, rect2, hm1, hm2 = obj1.rect, obj2.rect, obj1.hitmask, obj2.hitmask
    if not rect1.colliderect(rect2):
        return False
    rect = rect1.clip(rect2)

    w, h, x1, y1, x2, y2 = rect.width, rect.height, rect.x-rect1.x, rect.y-rect1.y, rect.x-rect2.x, rect.y-rect2.y

    while w > 0 and h > 0:
	for x in range(w):
		if hm1[x1+x][y1] and hm2[x2+x][y2]:
			return True
		if hm1[x1+x][y1+h-1] and hm2[x2+x][y2+h-1]:
			return True
	for y in range(1, h-1):
		if hm1[x1][y1+y] and hm2[x2][y2+y]:
			return True
		if hm1[x1+w-1][y1+y] and hm2[x2+w-1][y2+y]:
			return True
	w, h, x1, y1, x2, y2 = w-2, h-2, x1+1, y1+1, x2+1, y2+1
    return False

Is it faster than pygame's builtin rect.collidepoint method?