本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术,本文为大家讲解cocos2dx中,如何实现手势识别功能。
大家知道如何实现cocos2d中的手势识别吗?我在一篇文章中,看到过类似效果的实现方法:
http://www.cocos2d-iphone.org/forum/topic/8929
在github上找到了相关的补充资料:
https://github.com/xemus/cocos2d-GestureRecognizers/blob/master/README
此外,我创建了一个CCSprite(CCNode的子类别)的子类别:
1
2
3
4
5
6
7
8
9
10
11
12
|
|
1
2
3
4
- (void) swipe:(UIGestureRecognizer*)recognizer node:(CCNode*)node
{
NSLog(@" I never get called :( ");
}
在这种方法下,我设定的点击事件(tap event)始终不响应。
大家遇到过类似的问题吗?在cocos2d中实现swipe detection的手势识别很困难吗?
你需要将手势识别器(gesture recognizer)添加到"up the chain"中。不要只添加这些代码,而是要将他们和UIView结合在一起(例如:[[CCDirector sharedDirector] openGLView])
我的做法是:
1
2
3
4
5
6
7
8
9
10
|
- (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];
}
|
这段特殊的代码是用在超场景控制器中(scene controller),所以选择器的目标是筛选出,可以进行“自我”硬式编码(hard-code)的代码。
对于控制器的子类别,我是这样做的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
- (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
;
}
}
|
如果你不想人为控制一切操作,我建议你可以创建一种简单的类别,用来添加手势识别功能,详情可查看:
http://www.merowing.info/2012/03/using-gesturerecognizers-in-cocos2d/
或者可以在github上找到这种功能的实现源码:
https://github.com/krzysztofzablocki/CCNode-SFGestureRecognizers
原文链接:http://stackoverflow.com/questions/4985917/cocos2d-ios-gesture-recognisers
文章选自StackOverFlow社区,鉴于其内容对于开发者有所帮助,现将文章翻译于此,供大家参考及学习。9Tech将每日持续更新,读者可点击StackOverflow(简称:SOF)精选问答汇总,查看全部译文内容。同时,我们也招募志同道合的技术朋友共同翻译,造福大家!