12 iphone touch detection cocos2d-iphone
我只是不明白.我使用cocos2d开发iPhone/Pod上的小游戏.框架很棒,但我在触摸检测时失败了.我读到你只需要在CocosNode子类的实现中覆盖正确的函数(例如"touchesBegan").但它不起作用.我该怎么办?
功能:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}
Run Code Online (Sandbox Code Playgroud)
我完全错了吗?
谢谢!
Gen*_*ich 11
Layer是唯一可以触及的cocos2d类.
诀窍是,Layer的所有实例都会一个接一个地传递触摸事件,因此您的代码必须处理这个问题.
我是这样做的:
-(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;
}
Run Code Online (Sandbox Code Playgroud)
}
请注意,cocos2d库具有"ccTouchesEnded"实现,而不是Apple标准.它允许您返回一个BOOL,指示您是否处理了该事件.
祝好运!
你有没有将它添加到你的图层init方法?
// isTouchEnabled is an property of Layer (the super class).
// When it is YES, then the touches will be enabled
self.isTouchEnabled = YES;
// isAccelerometerEnabled is property of Layer (the super class).
// When it is YES, then the accelerometer will be enabled
self.isAccelerometerEnabled = YES;
Run Code Online (Sandbox Code Playgroud)
为了检测触摸,您需要从 UIResponder 继承(UIView 也是如此)。我对 cocos2D 不熟悉,但是快速浏览一下文档就会发现 CocosNode 并不是从 UIResponder 派生的。
经过进一步调查,Cocos 人员似乎创建了一个派生自 CocosNode 的 Layer 类。该类实现了触摸事件处理程序。但它们的前缀是 cc。
请参阅http://code.google.com/p/cocos2d-iphone/source/browse/trunk/cocos2d/Layer.h
另请参阅 menu.m 代码和下面的博客文章,了解更多信息:
http://blog.sapusmedia.com/2008/12/cocos2d-propagating-touch-events.html