The events of cocos2dx are quite pitted, and there are only four cases: begin, move, end and cancel. Then you will find that if your finger clicks on the outside of the button and does not let go of the button, then the button will not trigger the click. If you click on button A and swipe to button B, then the event will always be the move of button A. This is uncomfortable.
Suppose the following scenario:
The three buttons are not in a straight line and do not overlap, as follows:
Then how to do a finger swipe What about triggering the click effect?
We first assign the tags of the three buttons to 1000, 1001, and 1002 (for intuitiveness)
Then register the listener
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(false);
listener->onTouchBegan = [=](Touch* touch, Event* event){
listenerOnTouched(touch, event);
return true;
};
listener->onTouchMoved = [=](Touch* touch, Event* event){
listenerOnTouched(touch, event);
};< br />
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
Okay, now the registration is complete, and the listener is the begin and move events of this layer. When these two events are triggered Jump to the unified listenerOnTouched method, the following is the listenerOnTouched method:
void GameScene::listenerOnTouched(Touch* touch, Event* event)
{
Point locationInNode = this->convertTouchToNodeSpace( touch);
for (int i = 0; i <_levelData.answer.size(); i++) {
Sprite* answerSprite = static_cast(this->getChildByTag(1000+ i) );
if(answerSprite->getBoundingBox().containsPo int(locationInNode))
{
log("Point in %d! ! ",1000 + i);
}
}
}
The principle is to constantly use the click coordinates locationInNode to match the coordinates of the three buttons when the layer is clicked. Comparison
For beginners in cocos2dx, please advise if the code is not well written!