For example you have Player class and Enemy class and Dog class and Donkey class.
You want to attach touch functionality to each class, how do you do that?
I think I am not messing it with the question you asked on a different postā¦,and I hope you wonāt mind my answering to be intruding.
Anyways,
You donāt actually attach touch functionality to classesā¦ You actually attach it to the nodeā¦
So as long as some class is extending some node like layer, sprite, scene, etc then you can attach itā¦
Also, the way is simpleā¦
listener =EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
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);
Here HelloWorls class is extending my layer class(and layer is a node type)
You always have to remember that youāre adding your listener to _eventDispatcherā¦ and you donāt have to create object for thisā¦ you can straight away use _eventDispatcher or else you can use singleton class Director to get the eventdispatcherā¦
Now, see the āthisā keyword inside
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
This is the target where we are attaching the listener.
So, that means if youāre using āthisā keyword it means that āthisā is your class which is extending some nodeā¦
You can also use different node instead of āthisā.
I mean suppose youāre having a 3 sprites-all created and setted inside layer class.
And if you want to add event listener only to those 5 spritesā¦
Then follow the below thing
listener =EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
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,sprite1);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(),sprite2);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(),sprite3);
Noteā¦ I am not exactly sure whether it is clone() or whatā¦ But use auto complete and there should be something like clone or I guess this is correct
Did I answer your question fully?
@catch_up thanks for your efforts man. well I understand your example sprite1, sprite2 & sprite3 using the same _eventDispatcher. But note that since they use the same ālistenerā, they perform the same actions.
since the listener is attached to HelloWorld::onTouchBegan, ā¦ all of them will do the same thing when i press them.
What if i wanted to do this. when i press sprite1, the ātouchā will say āHELLOā.
if i press sprite2, the ātouchā will say āHANDSOMEā
if i press sprite3, the ātouchā will say āMEOWā.