cocos版本:3.2
VS版本:VS2013
一、 添加事件监听一般步骤为:创建时间监听器-->增事件监听器-->用导演获取时间派发器将事件监听器添加进去。
二、需要注意的地方有两点:
1.多点触摸中的onTouchesBegan方法没有返回值。如果带返回值,不会报错,但是会报链接错误。
2.多点触摸中的传入参数和单点触摸的传入参数不同。
具体看以下代码:
1.单点触摸监听器的处理触摸方法:
std::function<bool(Touch*,Event*)> onTouchBegan; std::function<void(Touch*,Event*)> onTouchMoved; std::function<void(Touch*,Event*)> onTouchEnded; std::function<void(Touch*,Event*)> onTouchCancelled;
2.多点触摸监听器的处理方法:
std::function<void(const std::vector<Touch*>&,Event*)> onTouchesBegan; std::function<void(const std::vector<Touch*>&,Event*)> onTouchesMoved; std::function<void(const std::vector<Touch*>&,Event*)> onTouchesEnded; std::function<void(const std::vector<Touch*>&,Event*)> onTouchesCancelled;
三、测试事件监听器
1.新建COCOS项目
TTFConfig tf("fonts/Marker Felt.ttf",36); Label *label = Label::createWithTTF(tf,"Cliked me"); label->setPosition(visibleSize / 2); addChild(label); EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [](Touch *t,Event *e){ if (e->getCurrentTarget()->getBoundingBox().containsPoint(t->getLocation())) { log("onTouchBegan"); return true; } return false; }; listener->onTouchMoved = [label](Touch *t,Event *e){ log("onToucheMoved"); label->setPosition(t->getLocation()); }; EventListenerTouchAllAtOnce *listener1 = EventListenerTouchAllAtOnce::create(); listener1->onTouchesBegan = [](std::vector<Touch *>ts,Event *e){ log("onTouchesBegan"); }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,label); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener1,this);运行即可。 原文链接:https://www.f2er.com/cocos2dx/342960.html