Austin
Austin

Reputation:

Detecting image touch (cocos2d)?

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

Upvotes: 1

Views: 2554

Answers (3)

David Higgins
David Higgins

Reputation: 1401

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) ...

Upvotes: 2

situee
situee

Reputation: 2740

This post will give you the answer Problem with cocos2D for iPhone and touch detection Problem with cocos2D for iPhone and touch detection

Upvotes: 0

Corey Floyd
Corey Floyd

Reputation: 25969

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.

Upvotes: 0

Related Questions