0
votes

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

2

2 Answers

0
votes

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);

0
votes

To deal with rotation the best approach would be to convert touch point into sprite local space (this will also handle correctly scaling and sprites hierarchy)

CGPoint ptConv = [cocosGuy convertTouchToNodeSpace: touch];
if (CGRectContainsPoint ([cocosGuy boundingBox], ptConv)
{
    retValue = YES;
}