我就是不明白。
我在iPhone/Pod上使用cocos2d来开发一个小游戏。这个框架非常棒,但是我在触摸检测方面失败了。我读到说你只需要在继承CocosNode的类的实现中重写正确的函数(例如“touchesBegan”)即可。但它不起作用。我可能做错了什么?
这是要翻译的内容:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}
我完全弄错了吗?
我就是不明白。
我在iPhone/Pod上使用cocos2d来开发一个小游戏。这个框架非常棒,但是我在触摸检测方面失败了。我读到说你只需要在继承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”实现,而不是苹果标准。 它允许您返回一个BOOL值,指示您是否处理了事件。
祝你好运!
// 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;
http://blog.sapusmedia.com/2008/12/cocos2d-propagating-touch-events.html
maw,CGPoint结构体的成员x和y是浮点数。使用@"%f"来格式化浮点数以用于printf/NSLog。
http://code.google.com/p/cocos2d-iphone/source/browse/#svn/trunk/tests/TouchesTest
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//Add a new body/atlas sprite at the touched location
CGPoint tapPosition;
for( UITouch *touch in touches ) {
CGPoint location = [touch locationInView: [touch view]];
tapPosition = [self convertToNodeSpace:[[CCDirector sharedDirector] convertToGL:location]]; // get the tapped position
}
}
我觉得这可能会对你有所帮助……
-让您的场景符合协议CCTargetedTouchDelegate
-将此行添加到您场景的init
中:
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
-实现以下函数:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
return YES;
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
//here touch is ended
}