有没有人设法使手势识别在cocos-2d中工作?
我在这里阅读了声称已实现的帖子:http://www.cocos2d-iphone.org/forum/topic/8929
我从这里的git中心打了补丁: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;
}
委托(delegate)方法:
- (void) swipe:(UIGestureRecognizer*)recognizer node:(CCNode*)node
{
NSLog(@" I never get called :( ");
}
我的点击事件从未被调用。
有人有这个工作吗?手动进行手势识别以进行滑动检测有多困难?
最佳答案
您需要将手势识别器附加到“上链”对象上。不要将它们附加到各个节点上;将它们附加到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];
}
此特定代码在场景 Controller 的父类(super class)中使用,因此选择器的目标被硬编码为“self”,但是您可以轻松地将其抽象为传入的对象。同样,您可以对上述内容进行推断,以轻松创建用于水龙头,捏等的手势识别器。
然后,在 Controller 的子类中,我只需要这样做:
- (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;
}
}
关于iphone - cocos2d-iOS-手势识别器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4985917/