Fork me on GitHub

cocos2d处理触摸事件

单触摸(Touch)事件:

  1. 导入 CCTouchDispatcher.h
    #import "CCTouchDispatcher.h" 
    官方文档说要导入,不过我没有导入这个头文件。
     
  2. 找个地儿,把下面这段代码塞进去
    -(void) registerWithTouchDispatcher 
    { 
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 
    }
  3. 在 init 方法中加入  
    self.isTouchEnabled = YES;
  4. 触摸事件处理方法
    - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
        return YES;
    }	
    
    -(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
    {
        ......
    }
    
    - (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
        ......  
    }
    
    第一个方法 ccTouchBegan 用来判断但前触摸事件是否时针对本层(如果采用多层设计,就要考虑,如果只有一个层,那么就直接返回 YES 就行了),如果是返回YES,接着就会运行下面两个方法;
    第二个ccTouchMoved,当你的手指在屏幕上滑动的时候就会调用这个方法。当然,如果不需要这样的操作,可以不用重写。
    第三个ccTouchEnded,当你的手指离开屏幕时调用。

附送一个坐标获取方法:

-(CGPoint) locationFromTouch:(UITouch*)touch
{
    CGPoint touchLocation = [touch locationInView: [touch view]];
    return [[CCDirector sharedDirector] convertToGL:touchLocation];
}

因为 上述事件中的参数 touch 得到触摸点的坐标。可以看到坐标点经过了一次坐标系转换,这时因为,Cocos2D是以OpenglES为底层图形库, 所以它采用的是OpenglES的坐标系统,即x轴向右,y轴向上。而苹果的Quarze2D则使用的是不同的坐标系统,x轴向右,y轴向下。

现在,你可以在 触摸事件处理方法中使用这个方法获取触摸坐标了。

posted on 2012-04-05 16:33  pengyingh  阅读(1455)  评论(0)    收藏  举报

导航