如何处理cocos2d中的点击持续时间?
我需要在用户将手指放在某个精灵上约1-2秒后做一些事情。
感谢。
答案 0 :(得分:1)
您需要以手动方式执行此操作:
update
或tick
中,将浮动ivar值增加dt
金额。如果它大于阈值(1.0或2.0秒),请检查浮动ivar值是否执行逻辑。如果您想要处理多个触摸,您可能需要一种方法来附加和区分BOOL标志和浮动ivar组合到每次触摸。
我建议在CCLayer和你的实现子类之间创建一个中间子类,这样你就可以从实现子类中隐藏机制,也可以轻松重用。
答案 1 :(得分:1)
为自己节省大量的手工工作,并使用UIGestureRecognizer进行此类操作。在这种特殊情况下,您将需要使用UILongPressGestureRecognizer。
顺便说一下,gesture recognizers are built-in, ready to use如果您使用Kobold2D。
答案 2 :(得分:0)
要使用UILongPressGestureRecognizer,您可以执行以下操作:
UILongPressGestureRecognizer* recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressFrom:)];
recognizer.minimumPressDuration = 2.0; // seconds
AppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.viewController.view addGestureRecognizer:recognizer];
你的长按处理程序可能如下所示:
-(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.
}
}
完成后,不要忘记将其删除。
AppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.viewController.view removeGestureRecognizer:recognizer];