如何在Cocos2D V3的CCScene中检测触摸事件?

4

我知道您曾经可以通过以下方式完成:

<CCLayerObject>.isTouchEnabled = YES;

与触摸调度程序的注册配合使用:

-(void)registerWithTouchDispatcher
{
    [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

然后只需获取回调即可:

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint point = [self convertTouchToNodeSpace:touch];
    NSLog(@"X:%ftY:%f", point.x, point.y);
}

但在V3中你需要做什么呢?


可能是在Cocos2d 2.0中"self.isTouchEnabled"的替代方法是什么?的重复问题。 - iPhoneProcessor
https://dev59.com/dGYq5IYBdhLWcg3wpyRE - iPhoneProcessor
@iPhoneProcessor 哈哈。那个问题是关于Cocos2D 2.0的...你忘记读标题了吗? - Alexandru
我已经在v3中解决了触摸问题,找到了答案。 - iPhoneProcessor
@iPhoneProcessor 抱歉,但那不算是一个“重复的问题”哈哈 - Alexandru
2个回答

4

看起来我所需要做的就是:

在CCScene的构造函数中,开启触摸功能:

[self setUserInteractionEnabled:YES];

在其中添加touchBegan方法:
- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    NSLog(@"touchBegan");
}

咔嚓!在V3中比在V2中更容易! 此外,也可以进行以下操作:
[self setMultipleTouchEnabled:YES];

3
在Cocos2d 3.0中,任何CCNode都可以接收触摸事件。你需要做的就是启用触摸功能:
self.userInteractionEnabled = YES;

您有四种不同的方法来处理触摸事件:

  • touchBegan:当用户触摸屏幕时调用

  • touchMoved::当用户在屏幕上移动手指时调用

  • touchEnded:当用户停止触摸屏幕时调用

  • touchCancelled:当用户仍在触摸屏幕,但由于一些问题,使得您的节点无法处理触摸事件(例如,触摸移动到节点边界之外)时调用

将触摸事件转换为节点空间的方法如下:

- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [touch locationInNode:self];
    currentHero.position = touchLocation;
}

您可以在这篇触摸教程中了解更多信息:https://makegameswith.us/gamernews/366/touch-handling-in-cocos2d-30

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接