views:

731

answers:

3

In cocos2d how would you detect a touch on an image? I'm having a lot of trouble with this so thanks in advance!

A: 

You need to overly invisible touch surfaces on top of the game using standard UIKit classes.

You then detect and interpret touches through those objects and pass the controls to your game.

If you have a more specific problem, you can provide more info or ask another question.

Corey Floyd
A: 

This post will give you the answer Problem with cocos2D for iPhone and touch detection http://stackoverflow.com/questions/377785/problem-with-cocos2d-for-iphone-and-touch-detection/379892

y.situ
+1  A: 

You implement the ccTouchesBegan/Ended/Moved methods within your Layer class, and then check the touch location against the container of the nodes you wish to detect touches for.

For example:

-(BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch touch = [touches anyObject];
  CGPoint location = [[Director sharedDirector] convertCoordinate: [touch locationInView: [touch view]]];

  CGRect mySurface = CGRectMake(100, 100, 50, 50);
  if(CGRectContainsPoint(mySurface)) {
    // do something
    return kEventHandled;
  }
  return kEventIgnored;
}

Now, this all changes in Cocos2D 0.8 (which is in active beta now) by using 'Touch Delegates' and examples can be seen in the 'Touches Test' (which appears to be a pong game from the source I just looked over).

I'm not sure why Corey said to use UIKit controls to detect touches, since Cocos2D has it's own way of handling them.

Only layers can receive touches - it is not advised that you use a Layer for each touchable 'game object' (ie; players and objects) ...

David Higgins