# In Cocos2D, how do I check for collisions against an arbitrary user-drawn shape?

I want to detect a collision between a sprite and a user-generated shape of some sort.

For example. There are 3 objects on the screen. The user takes their finger and draws an abnormal shape around 2 of the objects. I need to detect those 2 objects.

How do I approach this efficiently using Cocos2D?

There's a very easy solution for that particular example.

I'm assuming your arbitrary shape is just a series of points.

Draw a ray from each of your objects in any direction. If the number of times it intersects a line segment on your shape is even (including zero), you are outside of the shape.

If the number of times you intersect is odd, you are inside the object.

Ray/line segment collision is a pretty easy algorithm to find/implement.

Sure, I had to figure that out for my game Star Catch. There may be better ways of doing it but this is how I did it. I actually found the algorithm online (sorry I can't remember the source) I did a search for detecting a point inside a polygon.

I created a NSMutableArray to hold my point. I add the points in my touchevents.

- (BOOL) testNodeInLoop:(CCNode *)node {

CGPoint prev;

// This is more accurate point for the node
CGPoint absPoint = [node convertToWorldSpace:CGPointZero];

float x = absPoint.x;
float y = absPoint.y;

BOOL isIn = NO;

CGPoint cp;

for(int i = 0, j = [points count] - 1; i < [points count]; j = i++) {
[[points objectAtIndex:i] getValue:&cp];
[[points objectAtIndex:j] getValue:&prev];

if( ((cp.y > y) != (prev.y > y)) && (x < (prev.x -cp.x) * (y - cp.y) / (prev.y - cp.y) + cp.x)) {
isIn = !isIn;
}
}
return isIn;
}


Let me know if this is helpful.

The book "Real time collision detection" has a section about line/segment collision detection. Example via Google Books: http://ow.ly/2gjQf

For pixelwise collision checks there's a nice tutorial series on the XNA developer site.
http://creators.xna.com/en-US/tutorial/collision2dperpixeltransformed

One optimization you can use that wasn't used in those tutorials (oddly enough) is that in most cases only the outline needs to be checked, saving precious cycles.

Edited to add: Lousy answer, misread the question. The tutorials are still pretty decent though if you want to read up on per pixel coldet.