Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted
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;
}
share|improve this answer
    
Do I put this in a .m file or c++ file? –  Coder404 Jul 7 '12 at 15:55
    
this solution for cocos2d-x, but it's not hard write in objective-c –  Crazy D0G Jul 7 '12 at 15:57
    
how would you do it in objective c? –  Coder404 Jul 7 '12 at 15:58
    
try to rewrite this code using the syntax of objective-c. I do not write code to objective-c (write only in C + + and Java), I can only read it. mSprites is a vector whose elements are CCSprites. Try it, it should not be difficult. –  Crazy D0G Jul 7 '12 at 16:03
    
Maybe it's help you: iPhone Cocos2D user’s guide to Cocos2D-x (Part1) –  Crazy D0G Jul 7 '12 at 16:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.