2
votes

In cocos2d game development, CGRectContainsPoint method often used to detect if touch on a CCSprite.

I use code fllow to get a sprite's (which in a CCNode) rect property

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    CCLOG(@"ccTouchEnded");
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    CCLOG(@"location.x:%f, y:%f", location.x, location.y);
    CGRect rect;

    rect = CGRectMake(self.firstCard.face.position.x-(self.firstCard.face.contentSize.width/2), self.firstCard.face.position.y-(self.firstCard.face.contentSize.height/2),
                      self.firstCard.face.contentSize.width, self.firstCard.face.contentSize.height);
    if (CGRectContainsPoint(rect, location)) {
        CCLOG(@"first card touched");
        [firstCard open];
    }

    rect = CGRectMake(self.secondCard.face.position.x-(self.secondCard.face.contentSize.width/2), self.secondCard.face.position.y-(self.secondCard.face.contentSize.height/2),
                      self.secondCard.face.contentSize.width, self.secondCard.face.contentSize.height);
    if (CGRectContainsPoint(rect, location)) {
        CCLOG(@"second card touched");
        [secondCard open];
    }


}

I want to know if there is a convenient way to get a CCSprite 's rect straightforward?

2
You can get the sprite rect by [sprite_nm boundingBox]; method. I think it would work for you. It returns the whole Rect.Marine

2 Answers

2
votes

Please use boundingBox i think it will be a great option to use.

Like this:

- ( void ) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
   locationTouchBegan = [touch locationInView: [touch view]];

    //location is The Point Where The User Touched

    locationTouchBegan = [[CCDirector sharedDirector] convertToGL:locationTouchBegan];

    //Detect the Touch On sprite

    if(CGRectContainsPoint([sprite boundingBox], locationTouchBegan))
    {
        isSpriteTouched=YES;
    } 

}
2
votes

Kobold2D has a convenience method containsPoint as a CCNode extension (Objective-C category) which you can replicate in your project:

-(BOOL) containsPoint:(CGPoint)point
{
    CGRect bbox = CGRectMake(0, 0, contentSize_.width, contentSize_.height);
    CGPoint locationInNodeSpace = [self convertToNodeSpace:point];
    return CGRectContainsPoint(bbox, locationInNodeSpace);
}

Your code then be simplified to this and it will work with rotated and/or scaled sprites as well (the boundingBox method fails to test rotated and scaled sprites correctly).

if ([firstCard.face containsPoint:location]) {
        CCLOG(@"first card touched");
}