Touching a CGRect

| | August 6, 2015

In my cocos2d app I am trying to determine when a CCSprite is touched
Here is what I have:

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets) {
    CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2), 
                                   target.position.y - (target.contentSize.height/2), 
                                   27, 
                                   40);


CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
if (CGRectContainsPoint(targetRect, touchLocation)) {            
    NSLog(@"Moo cheese!");
    }
}
return YES;   
}

For some reason it does not work. Can someone help me?

One Response to “Touching a CGRect”

  1. bool Puzzle::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {
        if(isOnShapeTouched(pTouch)) {
            return true;
        }
    
        return false;
    }
    
    
    bool Puzzle::isOnShapeTouched(CCTouch* pTouch) {
        for(int i=0; i < mSprites.size(); i++) {
            if(CCRect::CCRectContainsPoint(mSprites.at(mSprites.size()-i-1)->boundingBox(), CCDirector::sharedDirector()->convertToGL(pTouch->locationInView()) ) ) {
                mCurrentSprite = mSprites.at(mSprites.size()-i-1);
    
                return true;
            }
        }
        return false;
    }
    

Leave a Reply