有没有人设法在cocos-2d中使用手势识别?
我在这里发了一篇声称已经实现的帖子,在这里:http://www.cocos2d-iphone.org/forum/topic/8929
我在git hub点了补丁:https://github.com/xemus/cocos2d-GestureRecognizers/blob/master/README
我创建了CCSprite
的子类(它是CCNode
的子类):
-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect {
if( (self=[super initWithTexture:texture rect:rect]) )
{
CCGestureRecognizer* recognizer;
recognizer = [CCGestureRecognizer
CCRecognizerWithRecognizerTargetAction:[[[UITapGestureRecognizer alloc]init] autorelease]
target:self
action:@selector(tap:node:)];
[self addGestureRecognizer:recognizer];
}
return self;
}
委托方法:
- (void) swipe:(UIGestureRecognizer*)recognizer node:(CCNode*)node
{
NSLog(@" I never get called :( ");
}
我的点击事件永远不会被调用。
有人有这个工作吗?手动进行手势识别以进行滑动检测有多难?
答案 0 :(得分:24)
您需要将手势识别器附加到“上链”中。不要将它们连接到各个节点;将它们附加到UIView(即[[CCDirector sharedDirector] openGLView])。
这就是我的所作所为:
- (UIPanGestureRecognizer *)watchForPan:(SEL)selector number:(int)tapsRequired {
UIPanGestureRecognizer *recognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:selector] autorelease];
recognizer.minimumNumberOfTouches = tapsRequired;
[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:recognizer];
return recognizer;
}
- (void)unwatch:(UIGestureRecognizer *)gr {
[[[CCDirector sharedDirector] openGLView] removeGestureRecognizer:gr];
}
此特定代码用于场景控制器的超类,因此选择器的目标被硬编码为“self”,但您可以轻松地将其抽象为传入的对象。此外,您可以推断上述内容,轻松创建水龙头,捏合等手势识别器。
在控制器的子类中,我只是这样做:
- (MyController *)init {
if ((self = [super init])) {
[self watchForPan:@selector(panning:) number:1];
}
return self;
}
- (void)panning:(UIPanGestureRecognizer *)recognizer {
CGPoint p;
CGPoint v;
switch( recognizer.state ) {
case UIGestureRecognizerStatePossible:
case UIGestureRecognizerStateBegan:
p = [recognizer locationInView:[CCDirector sharedDirector].openGLView];
(do something when the pan begins)
break;
case UIGestureRecognizerStateChanged:
p = [recognizer locationInView:[CCDirector sharedDirector].openGLView];
(do something while the pan is in progress)
break;
case UIGestureRecognizerStateFailed:
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
(do something when the pan ends)
(the below gets the velocity; good for letting player "fling" things)
v = [recognizer velocityInView:[CCDirector sharedDirector].openGLView];
break;
}
}
答案 1 :(得分:6)
如果您不想手动处理所有内容,我创建了一个简单的类别,可以为任何cocos2d版本添加手势识别器 阅读更多内容:
http://www.merowing.info/2012/03/using-gesturerecognizers-in-cocos2d/
或从github获取
https://github.com/krzysztofzablocki/CCNode-SFGestureRecognizers