问题描述
我只是不明白.我使用 cocos2d 在 iPhone/Pod 上开发一个小游戏.该框架很棒,但我在触摸检测方面失败了.我读到您只需要在子类 CocosNode 的类的实现中覆盖正确的函数(例如touchesBegan").但它不起作用.我会做错什么?
I just don't get it. I use cocos2d for development of a small game on the iPhone/Pod. The framework is just great, but I fail at touch detection. I read that you just need to overwrite the proper functions (e.g. "touchesBegan" ) in the implementation of a class which subclasses CocosNode. But it doesn't work. What could I do wrong?
功能:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}
我完全搞错了吗?
推荐答案
Layer 是 cocos2d 中唯一接触到的类.
Layer is the only cocos2d class which gets touches.
诀窍是 Layer 的所有实例一个接一个地传递触摸事件,所以你的代码必须处理这个.
The trick is that ALL instances of Layer get passed the touch events, one after the other, so your code has to handle this.
我是这样做的:
-(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
CGPoint cLoc = [[Director sharedDirector] convertCoordinate: location];
float labelX = self.position.x - HALF_WIDTH;
float labelY = self.position.y - HALF_WIDTH;
float labelXWidth = labelX + WIDTH;
float labelYHeight = labelY + WIDTH;
if( labelX < cLoc.x &&
labelY < cLoc.y &&
labelXWidth > cLoc.x &&
labelYHeight > cLoc.y){
NSLog(@"WE ARE TOUCHED AND I AM A %@", self.labelString);
return kEventHandled;
} else {
return kEventIgnored;
}
}
请注意,cocos2d 库有一个ccTouchesEnded"实现,而不是 Apple 标准.它允许您返回一个 BOOL 指示您是否处理了事件.
Note that the cocos2d library has a "ccTouchesEnded" implementation, rather than the Apple standard. It allows you to return a BOOL indicating whether or not you handled the event.
祝你好运!
这篇关于cocos2D for iPhone 和触摸检测的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!