Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

user shape in purple, game objects in green and red

How do I approach this efficiently using Cocos2D?

share|improve this question
up vote 10 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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

share|improve this answer

For pixelwise collision checks there's a nice tutorial series on the XNA developer site.

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.