Cocos2d-x Touch Event
Handle touch event
Override event method and set listener.
.h
class GameScene : public cocos2d::Layer
{
public:
// Override methods
bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event);
void onTouchMove(cocos2d::Touch *touch, cocos2d::Event *event);
void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event);
void onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *event);
}
onTouchBegan, onTouchMove, onTouchEnded, onTouchCancelled
You don’t need to override everything. Just only you need.
.cpp
bool GameScene::init()
{
// Cut several codes
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(GameScreen::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(GameScreen::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(GameScreen::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(GameScreen::onTouchCancelled, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
isTouching = false;
touchPosition = 0;
return true;
}
// Touch Events
bool GameScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
isTouching = true;
touchPosition = touch->getLocation().x;
return true;
}
void GameScene::onTouchMove(cocos2d::Touch *touch, cocos2d::Event *event) {
}
void GameScene::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event) {
isTouching = false;
}
void GameScene::onTouchCancelled(cocos2d::Touch *touch, cocos2d::Event *event) {
onTouchEnded(touch, event);
}
Multi Touch
How to Enable Multi-Touch
By default, it’s not required any setting for Android.(iOS is needed)
Node Rect
To detect touch position and node, this is helpful for you.
cocos2d::Rect Utils::getRect(cocos2d::Node* node) {
cocos2d::Point point = node->getPosition();
int width = node->getContentSize().width;
int height = node->getContentSize().height;
return cocos2d::Rect(point.x - (width / 2), point.y - (height / 2), width, height);
}
How to use?
bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
Point location = touch->getLocation();
Label *reset = (Label *)this->getChildByName("reset");
cocos2d::Rect resetRect = Utils::getRect(reset); // Rect
if (resetRect.containsPoint(location)) {
// Touch
}
return true;
}
