6
\$\begingroup\$

I'm trying to count the number of active touches in screen in order to perform an an action in case that there are two touches:

auto jumpListener = EventListenerTouchAllAtOnce::create();
    jumpListener->onTouchesBegan = [=](const std::vector<Touch*>& touches, Event* event)
    {
        CCLOG("Multi-touch detected %d", touches.size());
        if(touches.size() == 2)
        {
            this->_player->jump();
        }

    };

But even if I'm touching with two fingers, I get that only 1 touch has been made, any suggestions?

\$\endgroup\$
2
0
\$\begingroup\$

Most simple and reliable is to use the singular event "ccTouchBegan/ccTouchEnded" events, instead of the multiple one "ccTouchesBegan/ccTouchesEnded".

Also, make sure you do this in a class that inherits from Layer/LayerColor, otherwise it won't work.

virtual bool ccTouchBegan(cocos2d::Touch *pTouch, cocos2d::Event *pEvent);

bool MySceneLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *)
{
    // use location with 'pTouch->getLocationInView()'
    return true;
}
\$\endgroup\$
4
  • \$\begingroup\$ I think this method is for cocos2d-x 2.x \$\endgroup\$ – Jose M Pan Apr 25 '15 at 18:32
  • \$\begingroup\$ so basically increase a counter on touch began and reduce it on touch end? \$\endgroup\$ – John Demetriou Mar 22 '17 at 19:04
  • \$\begingroup\$ @JohnDemetriou Exactly. \$\endgroup\$ – Timotei Mar 23 '17 at 15:58
  • \$\begingroup\$ ok, did that part, but scaling the sprite when original distance and current distance between two fingers makes everything black \$\endgroup\$ – John Demetriou Mar 23 '17 at 18:44
0
\$\begingroup\$
//.h
int touchCount = 0;

//.cpp
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
listener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded, this);


void HelloWorld::onTouchesBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
touchCount++;
CCLOG("Multi-touch detected %d", touchCount);

if (touchCount == 2){

CCLOG("two finger are on the screen");

  }

}

void HelloWorld::onTouchesEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
touchCount--;
}

touchCount will keep track of how many touches are on the screen and you can do whatever you want with it.

\$\endgroup\$
1
  • \$\begingroup\$ Sorry about that fixed it. \$\endgroup\$ – ctapp1 Nov 5 '15 at 0:05
-1
\$\begingroup\$
auto jumpListener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);

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

Try this

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.