cocos2d-x学习笔记之touch分发器1

来源:互联网 发布:mac解压rar软件 编辑:程序博客网 时间:2024/06/05 23:46
原文地址:cocos2d-x学习笔记之touch分发器1作者:zjia5

cocos2d-x学习笔记之touch分发器1

       使用过CCLayer的都应该知道,CCLayer的众多父类中有CCTouchDelegate这么一个类,他使CCLayer能接收touch事件成为可能。cocos2d-x的touch事件是由CCTouchDispatcher这个touch分发器类来进行派发的,所有需要接收touch事件的对象都必须注册到CCTouchDispatcher中,而只有继承于CCTouchDelegate的对象才能被注册到touch分发器中。

        先看看cocos2d-x的touch事件的触发流程,我们能看得见的游戏界面我且称之为视图(view),touch的产生正是从视图开始的,在程序的消息处理中心检测到touch事件时,将事件整理成CCTouch的集合并传递给注册在视图内的touch分发器CCTouchDispatcher,这个 touch分发器是在导演类设置

openglView的时候注册的:

1
2
3
4
5
6
7
8
9
10
11
//1、直接设置touch分发器
void CCDirector::setTouchDispatcher(CCTouchDispatcher* pTouchDispatcher)
{
    //设置touch分发器
    if (m_pTouchDispatcher != pTouchDispatcher)
    {
        CC_SAFE_RETAIN(pTouchDispatcher);
        CC_SAFE_RELEASE(m_pTouchDispatcher);
        m_pTouchDispatcher pTouchDispatcher;
       
}
1
2
3
4
5
6
7
8
9
10
11
12
//2、导演类初始化的时候创建touch分发器
bool CCDirector::init(void)
{
    ......
    //导演类初始化的时候生成touch分发器
    m_pTouchDispatcher new CCTouchDispatcher();
    m_pTouchDispatcher->init();
                 
   ... ...
                 
    return true;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
void CCDirector::setOpenGLView(CCEGLView *pobOpenGLView)
{
    CCAssert(pobOpenGLView, "opengl view should not be null");
                 
    if (m_pobOpenGLView != pobOpenGLView)
    {
        ......
        //注册touch分发器到openglView中,接收view传递过来的touch事件
                 
         m_pobOpenGLView->setTouchDelegate(m_pTouchDispatcher);
        m_pTouchDispatcher->setDispatchEvents(true);
    }
}


        在查看touch分发器怎么处理touch事件之前,先了解传递的数据CCTouch,CCtouch的数据很简单,只有属性:

1
2
3
int m_nId;
CCPoint m_point;
CCPoint m_prevPoint;

CCTouch.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// returns the current touch location in screen coordinates
CCPoint CCTouch::getLocationInView() const
    //获取屏幕坐标
    return m_point; 
}
              
// returns the current previous location in screen coordinates
CCPoint CCTouch::getPreviousLocationInView() const
    //获取上一次的屏幕坐标
    return m_prevPoint; 
}
              
// returns the current touch location in OpenGL coordinates
CCPoint CCTouch::getLocation() const
    //获取在opengl坐标系中的坐标
    return CCDirector::sharedDirector()->convertToGL(m_point); 
}
              
// returns the previous touch location in OpenGL coordinates
0 0