Here Before
Here Before

Reputation: 43

Tap duration in cocos2d

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

Answers (3)

Danyal Aytekin
Danyal Aytekin

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

CodeSmile
CodeSmile

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

Lukman
Lukman

Reputation: 19174

You need to do it the manual way:

  1. Add a BOOL flag ivar and a float ivar in your CCLayer subclass.
  2. On touch began, set the flag to TRUE and reset the float ivar to 0.0
  3. On touch moved, ended or cancelled, set the flag to FALSE.
  4. In the 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

Related Questions