Search code examples
objective-ccocos2d-iphonecgpath

CGPath is not detected properly in cocos2d


Through help and suggestions, I created a path for my sprite so that only the non-transparent parts can be touched. This is the path I came up with:

    path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, endTouch.x, endTouch.y);
    CGPathAddLineToPoint(path, NULL, 0, 250);
    CGPathAddLineToPoint(path, NULL, 30, 0);
    CGPathCloseSubpath(path);

This works for all my other classes except for one. No matter where I tap, xcode keeps printing "outside" using this code:

for(int i = 0; i < [sprArray count]; i++)
{
    CCSprite *sprite = (CCSprite *)[sprArray objectAtIndex:i];
    if(CGRectContainsPoint([sprite boundingBox], location))
    {
        selectedSprite = sprite;
        location = [selectedSprite convertToNodeSpace:location];
        if (CGPathContainsPoint(path, NULL, location, NO) ) 
        {
            NSLog(@"inside");
        }
        else 
        {
            NSLog(@"outside");
        }

        break;
    }
}

I can only move my sprites if I get inside the if-condition, not else but even if I tap on the actual, colored sprite, it doesn't get the path I set. Are my measurements wrong? If not, what am I doing wrong? This is similar to the image I'm trying to use...

sample


Solution

  • This works only if image size is same. Depending on image size calculate coordinates.

    enter image description here

    CGPathMoveToPoint(path,    NULL,   54, 0 ); //1: 54 = distance from left, 0 = dis fem bottom
    CGPathAddLineToPoint(path, NULL,   28, 34 );
    CGPathAddLineToPoint(path, NULL,   36, 76 );
    CGPathAddLineToPoint(path, NULL,   51, 104 );
    CGPathAddLineToPoint(path, NULL,   46, 147 );
    CGPathAddLineToPoint(path, NULL,   67, 147 );
    CGPathAddLineToPoint(path, NULL,   70, 105 );
    CGPathAddLineToPoint(path, NULL,   56, 66 );
    CGPathAddLineToPoint(path, NULL,   52, 42 );
    CGPathAddLineToPoint(path, NULL,   67, 20 );
    CGPathAddLineToPoint(path, NULL,   92, 0 );
    CGPathCloseSubpath(path);