「cocos2dx」瓦片地图学习之地图滚动及触摸事件处理

cocos2d支持2中触摸事件处理机制:CCStandardTouchDelegate和CCTargetedTouchDelegate,分别用来处时单点触摸和多点触摸事件的处理。

CCLayer被设计用来接收用户输入,它是CCNode的子类,与CCNode类相比,只是添加了触摸及重力计等用户输入事件的处理功能,用户输入事件默认是关闭的,以下是分别开启多点及单点触摸事件处理的方法:

  • 在CCLayer中可以用setTouchEnabled(true)会开启多点触摸功能,多点触摸也是CCLayer的默认模式。
  • 使用CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true); 可以开启CCLayer的单点触摸功能。

在触摸功能开启后需要重写触摸事件处理方法,多点触摸事件的方法为:

virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent);

单点触摸事件处理方法为:

    //重写单点触屏处理事件
    virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
    virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); 
    virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); 
    virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);     //返回true则触摸点不再传递,false的话继续传递
    //void registerWithTouchDispatcher(void);

void registerWithTouchDispatcher(void);可以设置触摸事件的优先级,如果针对层的触摸事件接收不了,可能是被其他层截取了,可以用以下方法设置优先级:

 void HelloWorld::registerWithTouchDispatcher(void)
 
 {
 
 CCDirector* pDirector = CCDirector::sharedDirector();
 
 pDirector->getTouchDispatcher()->addTargetedDelegate(this, kCCMenuHandlerPriority + 1, true);
 
 }

触摸事件获取到的坐标系是以左上角为原点的,而openGL是以左下角为原点的,所以需要把获取到的坐标转换为openGL坐标系:

    //获取点在视图中的坐标(左上角为原点)
    CCPoint touchLocation = pTouch->getLocationInView();
    // 把点的坐标转换成OpenGL坐标(左下角为原点)
    touchLocation = CCDirector::sharedDirector()->convertToGL(touchLocation);
    // 把OpenGL的坐标转换成CCLayer的坐标
    CCPoint local = convertToNodeSpace(touchLocation)
    // 大小为100x100,坐标为(0, 0)的矩形

本文中瓦片地图滚动的参考资料为:http://blog.csdn.net/akof1314/article/details/8474232

效果显示视频:http://www.56.com/u41/v_OTE1ODkxOTg.html

原文地址:https://www.cnblogs.com/awakenjoys/p/cocos2d_tile.html