How to Attach Touch Listeners to my own Sprites

Cocos2dx V2.2.5

Hi guyz, i have a button sprite i’d like to attach a touch event listener to. . when i click it, i want something to happen, . like execute a getter method to display the property of an array object.

do you have code snippet i could study? Please don’t suggest using CCMenu cause I want to do something at the ‘touch begin’ and ‘touch ended’ functions :)),

thnx!

You can use bounding box of a particular sprite and make the things happen
if your finger is within the boundary of that sprite the functions will execute
for example
in your .h function declare the touch function

void ccTouchesEnded(CCSet* touches, CCEvent* event);
```

in your .cpp class add a sprite lets say buttonSprite
Now define the touchend function

void HelloWorld::ccTouchesEnded(CCSet* pTouch, CCEvent* event)
{
     CCTouch* touch = (CCTouch*)(pTouch->anyObject());
     CCPoint location = touch->getLocationInView();
     location =CCDirector::sharedDirector()->convertToGL(location);
    
    if(buttonSprite->boundingBox().containsPoint(location))
        {
        CCLOG(“Button clicked”);
//do your functionalities here
        }

}```
Similar way you can make a touchbegin function. ButtonClick will execute when you remove the finger from the sprite in above case.
In case of touchbegin it will work as soon as you touch the sprite
make sure to make your buttonSprite global. You can make in .h class

CCSprite * buttonSprite;
```
and create in .cpp class

buttonSprite::create(“CloseSelected.png”);
buttonSprite->setPosition(ccp(200,200));
addChild(buttonSprite);

also add a line in your **init()** function to make touch enable true

setTouchEnabled(true);

1 Like

yohoOO!! thnx rajan :smiley: you’re really helpful. now let me play with my new toys! >:DDD
tc

Im just curious.

why do you use CCSet in void HelloWorld::ccTouchesEnded(CCSet* pTouch, CCEvent* event){}
instead of CCTouch?

@reyanthonyrenacia

Depends. You can use both depending on your requirement. My requirement was to get a point when I wrote the line

pTouch->anyObject()
```
It returns a CCSet. thats why I took CCSet.
You can modify and use as per your requirements and can use CCTouch also