cpplibs: howto use Mask for pixelprecise collision

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
stelzbock
Posts: 4
Joined: Sat Jan 20, 2007 9:58 pm

cpplibs: howto use Mask for pixelprecise collision

Post by stelzbock »

I just started with the example from cpplibs. I really like this lib, because it's pure c++ and easy to use. Now I want to detect collisions on pixel level, but I wonder how the Mask class is intended to use.

Here's my first plan how to use the Mask class, but I don't think this is the right way:
1) find out overlapping area of 2 sprites (Images)
2) Create two Mask objects of the 2 Images with the overlapping area
3) call collide

But this way is not efficient because I have to create every Frame a new Mask object. Wouldn't it be better if the Mask is just created once, and then call collide every frame with the overlapping area of the two Mask objects?

Or does someone know a better way for testing if pixel of two images overlap?
User avatar
dot_blank
Posts: 498
Joined: Wed Sep 28, 2005 8:47 am
Location: Brasil

Post by dot_blank »

this is not precise as some sprites may contain
alpha channel set in some areas surrounding it
as 0 example would be a heart shaped object
course all sprites are squarish in nature so you would
be detecting mask collisions around this box and not
by the borders of the heart shaped object
10011011 00101010 11010111 10001001 10111010
stelzbock
Posts: 4
Joined: Sat Jan 20, 2007 9:58 pm

Post by stelzbock »

ok, then you can set just the mask bit of opaque pixels. I think that's not the problem.
fraca7
Posts: 21
Joined: Mon Oct 03, 2005 12:55 am
Location: Paris
Contact:

Post by fraca7 »

Hello. The 'Mask' class was pretty useless until now. I just upgraded it; you can grab the latest sources through SVN at this URL:

svn://fraca7.homeunix.net/python/trunk/cpplibs/

You instantiate the mask passing it an Image and (x, y, w, h) coordinates. It will then build a bitset of pixels which alpha value is greater than 'threshold' in the specified rectangle of the image. Two new optional parameters, 'x' and 'y', specify the position of the sprite. You can update this with the move(x, y) method.

Calling collide() returns the number of bits in common in the two masks, taking into account their respective position. So you just have to call move() to update the mask according to the sprite's current position and then collide() to see if the two sprites collide.

I didn't test this though...

HTH
Post Reply