0
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$
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;
}
\$\endgroup\$
5
  • \$\begingroup\$ Do I put this in a .m file or c++ file? \$\endgroup\$
    – Coder404
    Jul 7 '12 at 15:55
  • \$\begingroup\$ this solution for cocos2d-x, but it's not hard write in objective-c \$\endgroup\$
    – Crazy D0G
    Jul 7 '12 at 15:57
  • \$\begingroup\$ how would you do it in objective c? \$\endgroup\$
    – Coder404
    Jul 7 '12 at 15:58
  • \$\begingroup\$ 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. \$\endgroup\$
    – Crazy D0G
    Jul 7 '12 at 16:03
  • \$\begingroup\$ Maybe it's help you: iPhone Cocos2D user’s guide to Cocos2D-x (Part1) \$\endgroup\$
    – Crazy D0G
    Jul 7 '12 at 16:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .