cocos2dx 3.0调用点击事件
设置可点击
this->setTouchEnabled(true)
1.创建Eventlistener监听器
2.设置该监听器可以向下传递事件
listen->setSwallowTouches(true);
3.添加onTouchesBegan onTouchesCanceled onTouchesMoved onTouchesEnded 等事件的实现,注:必须实现一个,不然会报错,原因是底层判断了如果一个都没有实现就报错(具体看完忘记了。。。),注意onTouchesBegan 的时候会返回一个bool类型,如果为true就不会继续向下传递,如果false就继续往下传递
4.获取全局的事件分发器
EventDispatcher* eventdispatcher = Director::getInstance()->getEventDispatcher();
5.最后将事件监听器注册到该事件分发器中,第二个参数为需要监听的node
this->setTouchEnabled(true);
EventDispatcher* eventdispatcher = Director::getInstance()->getEventDispatcher();
auto listen = EventListenerTouchOneByOne::create();
listen->setSwallowTouches(true);
//listen->onTouchesBegan = CC_CALLBACK_1(HelloWorld::onTouchBegan,this);
/*listen->onTouchesBegan = [](Touch* touches, Event *event) {
CCLOG("onTouchesBegan!!!!");
};*/
auto leftarrow = rootNode->getChildByName("left_arrow");
auto rightarrow = rootNode->getChildByName("right_arrow");
CCLOG("left_arrow zooder=%d", leftarrow->getLocalZOrder());
listen->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
listen->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
eventdispatcher->addEventListenerWithSceneGraphPriority(listen, leftarrow);
eventdispatcher->addEventListenerWithSceneGraphPriority(listen->clone(), rightarrow);
注:在onTouchBegan中获取到的event->getCurrentTarget()不一定是点击到的node,需要自行进行判断,同时确定要不要传到下一层,这样可以确定开始点击的和点击结束的是同个精灵
bool HelloWorld::onTouchBegan(cocos2d::Touch* touches, cocos2d::Event *event) {
CCLOG("onTouchesBegan!!!!");
auto leftarrow = rootNode->getChildByName("left_arrow");
auto rightarrow = rootNode->getChildByName("right_arrow");
auto target = static_cast<Sprite*>(event->getCurrentTarget());
Point p = target->convertToNodeSpace(touches->getLocation());
Size s = target->getContentSize();
Rect r = Rect(0, 0, s.width, s.height);
if (r.containsPoint(p)) {
if (leftarrow == target) {
arrow = -1;
CCLOG("left!!!!");
}
if (rightarrow == target) {
arrow = 1;
CCLOG("right!!!!");
}
return true;
}
return false;
}
void HelloWorld::onTouchEnded(cocos2d::Touch* touches, cocos2d::Event *event) {
CCLOG("onTouchEnded!!!!");
auto leftarrow = rootNode->getChildByName("left_arrow");
auto rightarrow = rootNode->getChildByName("right_arrow");
auto target = static_cast<Sprite*>(event->getCurrentTarget());
if (leftarrow == target) {
arrow = 0;
return;
}
if (rightarrow == target) {
arrow = 0;
return;
}
}