Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect touch Cocos2d-x

I'm using Cocos2d-x and trying to detect touches in my HelloWorld project. Though I'm having no luck.

.h

class HelloWorld : public CCLayer{

private:
    CCSpriteBatchNode * _batchNode;
    CCSprite *_turkey;
    virtual void ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event);

.ccp

void HelloWorld::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event){
    CCLog("this");
}

but the thing is that when I click the screen 'this' never shows up in the log. What am i missing here?

thanks!

Edit,

Im using this tutorial. http://www.raywenderlich.com/11338/cocos2d-x-for-ios-and-android-space-game

like image 537
James Dunay Avatar asked Jun 21 '12 15:06

James Dunay


3 Answers

You have to register with CCTouchDispatcher in order to receive touches:

Write this in your init() method in order to receive touches:

CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(this, 0);

Also I recommend you to receive touch event via targeted touch delegate methods:

virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);

In order these methods to be called you have to register with touch dispatcher a bit different:

CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);

EDIT

In new cocos version CCTouchDispatcher is located in CCDirector:

It should look something like this:

CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
like image 59
Andrew Avatar answered Sep 21 '22 23:09

Andrew


So something super simple, just added

this->setIsTouchEnabled(true);

to my init(); function.

like image 22
James Dunay Avatar answered Sep 24 '22 23:09

James Dunay


'this' never shows up in the log

hints You might be using a different version of Cocos2D library. Please go to cocos2d.h on your project and confirm. (the sample was written on 1.0.1). If you are on a different version, (guessing) you might have to use different ccTouchesBegan signature and/or fix more than just setIsTouchEnabled to make it work. I just downloaded the sample, and the ccTouchesBegan call works perfect - without any changes.

like image 25
danfelabs Avatar answered Sep 25 '22 23:09

danfelabs