c++ - Touch Event on Sprite with Cocos2d-x 3.x? -


in scene have vector multiple custom sprites. when tap on 1 of them, want action fired on element on scene, can sprite in vector, or node. have been researching best way this, i'm not quite sure how implement it. options are:

  • add touch listener scene, , verify if tapped inside bounds of sprite rect. containspoint(point). , after that, have sprite tapped action want. me, doesn't seems clean way. , if 2 sprites overlaped, have verify if sprite behind or in front in order retrieve desired sprite. followed example: touch event example

  • add touch listener in subclass of sprite (my custom sprite). , add ontouchbegan , ontouchended inside it. way, don't know how modify attribute of sprite, or element in scene (is possible use delegates objective-c does?). followed example: subclass sprite example

my main problem don't understand how make node interact node in scene. have seen lot of tutorials, in of them, when interact node, changes attributes, not other nodes' attributes.

thanks in advance.

i shall propose "eventcustom" way :)

you can add in touchbegan / touchended methods (wherever put them... got point...) additional code passing eventcusto _eventdispatcher , announced world ;)

eventcustom *e = new eventcustom("myawesomeevent"); e->setuserdata(ptrmyfantasticdata); //this function takes void pointer. cheers :) _eventdispatcher->dispatchevent(e); 

you may subclass eventcustom class hardly necessary. can hang object setuserdata().

now objects need react event can listen

_mycustomlistener = eventlistenercustom::create(                 "myawesomeevent",                  cc_callback_1(                      listeningclass::onmyawesomeevent,                                        )              ); _eventdispatcher->addeventlistenerwithxxxxxpriority(_mycustomlistener, xxx); //screengraphpriority / fixedpriority depends on situation. either should work. 

it's practice remove listeners when go off, somewhere, perhaps in onexit(), removed touch listeners remove listener too, as

_eventdispatcher->removeeventlistener(_mycustomlistener); 

going bit off track, clarification: cc_callback_x bit tricky names. x indicates no. of args target function get. here, event dispatcher pass 1 arg i.e. ptr object of eventcustom handed it, use cc_callback_1. next arg - here "this" - object on method invoked. in short, may callback going result function call this->onmyawesomeevent(e);

for cc_callback_2 onwards, can specify additional args, 3rd arg onwards.

coming issue @ hand, listeningclass::onmyawesomeevent like

void listeningclass::onmyawesomeevent(eventcustom *e) {     myfantasticdata *d = (myfantasticdata *) e->getuserdata();     cclog("[listeningclass::onmyawesomeevent] %d", d->getmypreciousint()); } 

hope helps :)


Comments