EventListenerTouchOneByOne::create() 單點觸控
阿新 • • 發佈:2019-01-08
void HelloWorld::onEnter() { Layer::onEnter(); log("HelloWorld onEnter"); // 建立一個事件監聽器 OneByOne 為單點觸控 auto listener = EventListenerTouchOneByOne::create(); // 設定是否吞沒事件,在 onTouchBegan 方法返回 true 時吞沒 listener->setSwallowTouches(true); // onTouchBegan 事件回撥函式 listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::touchBegan, this); // onTouchMoved 事件回撥函式 listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::touchMoved, this); // onTouchEnded 事件回撥函式 listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::touchEnded, this); // 註冊監聽器 EventDispatcher* eventDispatcher = Director::getInstance()->getEventDispatcher(); eventDispatcher->addEventListenerWithSceneGraphPriority(listener, getChildByTag(kBoxA_Tag)); eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), getChildByTag(kBoxB_Tag)); eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), getChildByTag(kBoxC_Tag)); } bool HelloWorld::touchBegan(Touch* touch, Event* event) { // 獲取事件所繫結的 target auto target = static_cast<Sprite*>(event->getCurrentTarget()); // 獲取當前點選點所在相對按鈕的位置座標 Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); // 點選範圍判斷檢測 if (rect.containsPoint(locationInNode)) { log("sprite x = %f, y = %f ", locationInNode.x, locationInNode.y); log("sprite tag = %d", target->getTag()); target->runAction(ScaleBy::create(0.06f, 1.06f)); return true; } return false; } void HelloWorld::touchMoved(Touch *touch, Event *event) { log("onTouchMoved"); auto target = static_cast<Sprite*>(event->getCurrentTarget()); // 移動當前按鈕精靈的座標位置 target->setPosition(target->getPosition() + touch->getDelta()); } void HelloWorld::touchEnded(Touch *touch, Event *event) { log("onTouchEnded"); auto target = static_cast<Sprite*>(event->getCurrentTarget()); log("sprite onTouchesEnded.. "); Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0, 0, s.width, s.height); // 點選範圍判斷檢測 if (rect.containsPoint(locationInNode)) { log("sprite x = %f, y = %f ", locationInNode.x, locationInNode.y); log("sprite tag = %d", target->getTag()); target->runAction(ScaleTo::create(0.06f, 1.0f)); } } void HelloWorld::onExit() { Layer::onExit(); log("HelloWorld onExit"); Director::getInstance()->getEventDispatcher()->removeAllEventListeners(); }