Duration of pressing cocos2d

Any ideas on how to handle retraction time in cocos2d?

I need to do something after the user swipes his finger on a specific sprite for about 1-2 seconds.

Thanks.

+4
source share
3 answers

You need to do it manually:

  • Add the BOOL ivar and float ivar flags to your CCLayer subclass.
  • When starting a touch, set the flag to TRUE and reset float ivar to 0.0
  • When you move, end, or cancel the touch, set the flag to FALSE.
  • In update or tick increase float ivar to dt . Make sure that it is a float ivar value to execute your logic if it is greater than your threshold value (1.0 or 2.0 seconds).

If you want to handle multiple touches, you may need a way to attach and differentiate the BOOL and float ivar flags for each click.

I would suggest creating an intermediate subclass between CCLayer and the implementation subclass so that you can hide the mechanism from the implementation subclass, as well as for easy reuse.

+1
source

Save most of the manual work and use UIGestureRecognizers for such things. In this particular case, you will want to use the UILongPressGestureRecognizer .

Btw, gesture recognizers are built-in, ready to use if you use Kobold2D .

+1
source

To use 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 print handler might 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 are done, be sure to remove it.

 AppDelegate* appDelegate = [[UIApplication sharedApplication] delegate]; [appDelegate.viewController.view removeGestureRecognizer:recognizer]; 
0
source

Source: https://habr.com/ru/post/1384262/


All Articles