Reputation: 43
Any ideas how to handle tap duration in cocos2d?
I need to do something after the user holds his or her finger on a certain sprite for about 1-2 secs.
Thanks.
Upvotes: 4
Views: 1439
Reputation: 4215
To use a UILongPressGestureRecognizer, you can do something like this:
UILongPressGestureRecognizer* recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressFrom:)];
recognizer.minimumPressDuration = 2.0; // seconds
AppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.viewController.view addGestureRecognizer:recognizer];
Your long press handler could look like this:
-(void)handleLongPressFrom:(UILongPressGestureRecognizer*)recognizer
{
if(recognizer.state == UIGestureRecognizerStateEnded)
{
CCLOG(@"Long press gesture recognized.");
// Get the location of the touch in Cocos coordinates.
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
CCDirector* director = [CCDirector sharedDirector];
touchLocation = [director convertToGL:touchLocation];
touchLocation = [[director runningScene] convertToNodeSpace:touchLocation];
// Your stuff.
}
}
When you're finished, don't forget to remove it.
AppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.viewController.view removeGestureRecognizer:recognizer];
Upvotes: 0
Reputation: 64477
Save yourself a lot of manual work and use the UIGestureRecognizers for things like these. In this particular case you will want to use the UILongPressGestureRecognizer.
Btw, gesture recognizers are built-in, ready to use if you use Kobold2D.
Upvotes: 1
Reputation: 19174
You need to do it the manual way:
update
or tick
, increase the float ivar value by the dt
amount. Check if that float ivar value to perform your logic if it is larger than your threshold value (1.0 or 2.0 seconds).If you want to handle multiple touches, you might need a way to attach and differentiate the BOOL flag and float ivar combination to each touch.
I'd suggest creating an intermediate subclass between CCLayer and your implementation subclass so that you can hide the mechanism from the implementation subclass and also to allow easy reuse.
Upvotes: 1