Wednesday, May 6, 2015

Cocos2dx: Detecting Multiple Touches


In .h file:

class HelloWorld : public cocos2d::Layer
{
public:
    // 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
    CREATE_FUNC(HelloWorld);
    
    void onTouchesBegan(const std::vector<cocos2d::Touch*> &touches, cocos2d::Event *event);
    void onTouchesMoved(const std::vector<cocos2d::Touch*> &touches, cocos2d::Event *event);
    void onTouchesEnded(const std::vector<cocos2d::Touch*> &touches, cocos2d::Event *event);

};


Implementation:

bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    
    auto listener = EventListenerTouchAllAtOnce::create();

    //Using CC_CALLBACK_2 because onTouchesXXX receives 2 params
    listener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
    listener->onTouchesMoved = CC_CALLBACK_2(HelloWorld::onTouchesMoved, this);
    listener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    return true;
}

void HelloWorld::onTouchesBegan(const std::vector<cocos2d::Touch*> &touches, 
                                cocos2d::Event* event){
    CCLOG("MULTI TOUCH BEGAN");
}

void HelloWorld::onTouchesMoved(const std::vector<cocos2d::Touch*> &touches, 
                                cocos2d::Event* event){
    CCLOG("MULTI TOUCHES HAVE MOVED");
}

void HelloWorld::onTouchesEnded(const std::vector<cocos2d::Touch*> &touches, 
                                cocos2d::Event* event){
    CCLOG("MULTI TOUCHES HAVE ENDED");

}

No comments:

Post a Comment