Search code examples
iphoneobjective-ccocos2d-iphonecollision-detectionsprite

cocos2d sprite collision detection


I am currently creating a point and click app for the iphone using cocos2d. However with my current implementation the collision detection condition is only true if i click on the top left corner and not anywhere within the sprite. If i set the anchor position to 0 this makes things better however this causes my rotating sprite feature to break.

here is my code, can anyone spot anything wrong here? in my init code

if( (self=[super init])) 
{       

        cocosGuy = [TouchableSprites spriteWithFile: @"Icon.png"];  
        //[cocosGuy setAnchorPoint:CGPointMake(0, 0)];
        cocosGuy.position = ccp( 200, 300 );
    //[cocosGuy setPosition: ccp(100,100)];
        [self addChild:cocosGuy];
    self.isTouchEnabled = YES;
}

in touchBegan i determine whether or not an image has been touched

    CGPoint pt = [touch locationInView:[touch view]];
    CGPoint ptConv = [[CCDirector sharedDirector] convertToGL:pt];

CGSize size = [cocosGuy contentSize];
CGPoint point = [cocosGuy position];
CGRect rect = CGRectMake(point.x, point.y, size.width, size.height); 

if (CGRectContainsPoint(rect, ptConv))
{
    retValue = YES;
}   

Any help would be greatly appreciated


Solution

  • The rect that you are generating takes the touch point and then makes the rectangle from that point as the corner.

    CCSprites have their origin point in the middle of the image. So you need to account for that when making your rect

    CGRect rect = CGRectMake(point.x - (size.width / 2), point.y - (size.height / 2), size.width, size.height);