我只是不明白.我使用cocos2d开发iPhone/Pod上的小游戏.框架很棒,但我在触摸检测时失败了.我读到你只需要在CocosNode子类的实现中覆盖正确的函数(例如"touchesBegan").但它不起作用.我该怎么办?
功能:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}
我完全错了吗?
谢谢!
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; }
}
请注意,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;