基本的两个坐标系:屏幕坐标系和GL坐标系。
屏幕坐标系:x轴朝右,y轴朝下。默认原点在左上角。
GL坐标系
调用CCNode类的setPosition函数,它使用的就是GL坐标系。
在处理触摸事件时CCTouch对象中的坐标就是屏幕坐标系。
讲屏幕坐标系转换成GL坐标系调用:convertTouchToNodeSpace方法,它是CCNode的成员方法:
其实现如下
- (CGPoint)convertTouchToNodeSpace:(UITouch *)touch
{
CGPoint point = [touch locationInView: [touch view]];
point = [[CCDirector sharedDirector] convertToGL: point];
return [self convertToNodeSpace:point];
}
调用时:
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchPoint =[self convertTouchToNodeSpace:touch];
return YES;
}
cocos2d的事件在CCLayer中处理。
1.CCLayer的isTouchEnabled,和registerWithTouchDispatcher 默认是不响应,需要手动设置
self.isTouchEnabled = YES;
-(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
priority:1
swallowsTouches:YES];
[[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self
priority:0];
[super registerWithTouchDispatcher];
}
2.CCLayer需要实现CCStandardTouchDelegate,CCTargetedTouchDelegate两个协议
CCStandardTouchDelegate是 实现多点触控,委托方法如下:
@optional
- (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;
CCTargetedTouchDelegate是 一点触控,委托方法如下:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
@optional
// touch updates:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;