易采站长站为您分析iOS开发中使用cocos2d添加触摸事件的方法,cocos2d是制作iOS游戏的利器,需要的朋友可以参考下
此项设定最好在init方法中设置。你可以在任何时间将其设置为NO或者YES。
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent*)event
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent*)event
-(void) ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent*)event
-(CGPoint) locationFromTouches:(NSSet *)touches
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView: [touch view]];
return [[CCDirector sharedDirector] convertToGL:touchLocation];
}
CCLayer类是用来接收触摸输入的。不过你要首先启用这个功能才可以使用它。你通过设置isTouchEnabled为YES来让层接收触摸事件:
复制代码 self.isTouchEnabled = YES;
此项设定最好在init方法中设置。你可以在任何时间将其设置为NO或者YES。
一旦启用isTouchEnabled属性,许多与接收触摸输入相关的方法将会开始被调用。这些事件包括:当新的触摸开始的时候,当手指在触摸屏上移动的时候,还有在用户手指离开屏幕以后。很少会发生触摸事件被取消的情况,所以你可以在大多数情况下忽略它,或者使用ccTouchesEnded方法来处理。
当手指首次触摸到屏幕时调用的方法:
复制代码-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
手指在屏幕上移动时调用的方法:
复制代码-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent*)event
当手指从屏幕上提起时调用的方法:
复制代码-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent*)event
当触摸事件被取消时调用的方法:
复制代码-(void) ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent*)event
取消事件的情况很少发生,所以在大多数情况下它的行为和触摸结束时相同。
因为触摸事件由Cocoa TouchAPI接收,所以触摸的位置必须被转换为OpenGL的坐标。
以下是一个用来转换坐标的方法:
复制代码
-(CGPoint) locationFromTouches:(NSSet *)touches
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView: [touch view]];
return [[CCDirector sharedDirector] convertToGL:touchLocation];
}










