Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect touches in a CCScene on Cocos2D V3?

I know that you used to be able to do it through:

<CCLayerObject>.isTouchEnabled = YES;

...in conjunction with a registration to the touch dispatcher:

-(void)registerWithTouchDispatcher
{
    [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

...and then just get the callbacks:

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint point = [self convertTouchToNodeSpace:touch];
    NSLog(@"X:%ftY:%f", point.x, point.y);
}

But what do you need to do in V3?

like image 686
Alexandru Avatar asked Mar 21 '23 13:03

Alexandru


2 Answers

Looks like all I had to do was:

In the CCScene constructor, enable touches:

[self setUserInteractionEnabled:YES];

Add the touchBegan method in:

- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    NSLog(@"touchBegan");
}

Ta-da! Much easier in V3 than in V2!

Optionally, can also:

[self setMultipleTouchEnabled:YES];
like image 181
Alexandru Avatar answered Apr 28 '23 23:04

Alexandru


In Cocos2d 3.0 any CCNode can receive touches. All you need to do is enable touches:

self.userInteractionEnabled = YES;

Then you have four different methods to handle touches:

  • touchBegan: gets called when the user touches the screen

  • touchMoved:: gets called when the user moves his finger over the screen

  • touchEnded: gets called when the user stops touching the screen

  • touchCancelled: gets called when user still is touching the screen
    but some other issue stops your Node from handling the touch (e.g.
    touch moved outside the boundaries of your Node)

Converting the touch to the Node space works like this:

- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [touch locationInNode:self];
    currentHero.position = touchLocation;
}

You can read more in this touch tutorial: https://makegameswith.us/gamernews/366/touch-handling-in-cocos2d-30

like image 36
Ben-G Avatar answered Apr 28 '23 21:04

Ben-G