cocos2dx源码分析:事件监听器EventListener

目前cocos2dx中有8种事件

    enum class Type {
        UNKNOWN,
        TOUCH_ONE_BY_ONE,
        TOUCH_ALL_AT_ONCE,
        KEYBOARD,
        MOUSE,
        ACCELERATION,
        FOCUS,
        GAME_CONTROLLER,
        CUSTOM
    };

TOUCH_ONE_BY_ONE是点击事件,一次处理一个点,也就是单点触摸,实现类为EventListenerTouchOneByOne,可以设置4个事件回调函数:

    typedef std::function<bool(Touch*, Event*)> ccTouchBeganCallback;
    typedef std::function<void(Touch*, Event*)> ccTouchCallback;
    ccTouchBeganCallback onTouchBegan;
    ccTouchCallback onTouchMoved;
    ccTouchCallback onTouchEnded;
    ccTouchCallback onTouchCancelled;

TOUCH_ALL_AT_ONCE也是点击事件,但是一次可以处理多个点,也就是多点触摸,实现类为EventListenerTouchAllAtOnce,可以设置4个事件回调函数

 typedef std::function<void(const std::vector<Touch*>&, Event*)> ccTouchesCallback;
    ccTouchesCallback onTouchesBegan;
    ccTouchesCallback onTouchesMoved;
    ccTouchesCallback onTouchesEnded;
    ccTouchesCallback onTouchesCancelled;

KEYBOARD用来监听键盘事件,需要有键盘的设备才能触发,实现类为EventListenerKeyboard,可以设置按键按下和按键松开回调函数

std::function<void(EventKeyboard::KeyCode, Event*)> onKeyPressed;
std::function<void(EventKeyboard::KeyCode, Event*)> onKeyReleased;

MOUSE用来监听鼠标事件,需要有鼠标的设备才能触发,实现类为EventListenerMouse,可以设置4个回调函数

std::function<void(EventMouse* event)> onMouseDown;
std::function<void(EventMouse* event)> onMouseUp;
std::function<void(EventMouse* event)> onMouseMove;
std::function<void(EventMouse* event)> onMouseScroll;

ACCELERATION响应加速器事件,实现类为EventListenerAcceleration,可以设置一个回调函数

std::function<void(Acceleration*, Event*)> onAccelerationEvent;

FOCUS响应ui焦点改变事件,实现类为EventListenerFocus,回调函数为

std::function<void(ui::Widget*, ui::Widget*)> onFocusChanged;

CUSTOM响应自定义的事件,实现类为EventListenerCustom,回调函数为

std::function<void(EventCustom*)> _onCustomEvent;

GAME_CONTROLLER,ios和android才有

使用事件监听器时,先创建具体的监听器
auto listener = EventListenerTouchOneByOne::create();
然后设置监听器的回调函数
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan1, this);
listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
最后添加到派发器中
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
此后,如果有对应的事件发生,监听器回调函数就会被调用

你可能感兴趣的:(cocos2d-x)