Wednesday, May 6, 2015

Cocos2dx: Detecting Single Touches

Create the following in the .h file:

class HelloWorld : public cocos2d::Layer
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    virtual bool init();
    // implement the "static create()" method manually
    bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event);
    void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event);
    void onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event);


Create the following in the implementation file:

// on "init" you need to initialize your instance
bool HelloWorld::init()
    if ( !Layer::init() )
        return false;
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    return true;

bool HelloWorld::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event){
    CCLOG("onTouchBegan x = %f, y = %f", touch->getLocation().x,
    return true;

void HelloWorld::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event){
    CCLOG("onTouchMoved x = %f, y = %f", touch->getLocation().x,

void HelloWorld::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event){
    CCLOG("onTouchEnded x = %f, y = %f", touch->getLocation().x,

Alternatively, you can do this:

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this);

instead of:

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

No comments:

Post a Comment