// Gamescene. h # include "cocos2d. H "using_ns_cc; Class gamescene: Public cocos2d: layer {public: static cocos2d: Scene * createscene (); Virtual bool Init (); Virtual void ontouchesbegan (const STD :: vector <touch *> & touches, event * unused_event); Virtual void ontouchesmoved (const STD: vector <touch *> & touches, event * unused_event ); virtual void ontouchesended (const STD: vector <touch *> & touches, event * unused_event); Virtual void ontouchescancelled (const STD: vector <touch *> & touches, event * unused_event); void menucallback (ref * psender); create_func (gamescene); Private: // note that the auto keyword size cannot be used; sprite * sprite ;};
// Gamescene. CPP // refer to mutitouchtest. CPP # include "gamescene. H "using_ns_cc; cocos2d: Scene * gamescene: createscene () {auto scene = scene: Create (); // create a scenario auto layer = gamescene :: create (); // create a layer scene-> addchild (layer); Return scene;} // initialize the current layer bool gamescene: Init () {If (! Layer: Init () // initialize the parent class return false; // obtain the screen size = Director: getinstance ()-> getvisiblesize (); // auto size = Director: getinstance ()-> getwinsize (); Auto sprite = sprite: Create ("icon.png"); sprite-> setposition (vec2 (size. width/2, size. height/2); sprite-> settag (12); this-> addchild (sprite); // 1. register the listening event object auto listener = eventlistenertouchallatonce: Create (); // multi-point touch // 2. define the listener object callback method listener-> ontouches Began = cc_callback_2 (gamescene: callback, this); listener-> listener = cc_callback_2 (gamescene: callback, this); listener-> ontouchesended = cc_callback_2 (gamescene: callback, this); listener-> ontouchescancelled = cc_callback_2 (gamescene: ontouchescancelled, this); // 3. register in the event listener (the event listener includes touch events, Keyboard Events, acceleration events, mouse response events, and custom events) _ eventdispatcher-> addeventlistenerwithscenegraphpriority (Listener, this); Return true;} void gamescene: menucallback (ref * psender) {} void gamescene: ontouchesbegan (const STD: vector <touch *> & touches, event * unused_event) {for (Auto & item: touches) // traverses all the members in the container !!! Multiple genie {auto touch = item; Auto location = touch-> getlocation (); Auto sprite = This-> getchildbytag (12) are displayed at the same time ); sprite-> setposition (location) ;}} void gamescene: ontouchesmoved (const STD: vector <touch *> & touches, event * unused_event) {} void gamescene :: ontouchesended (const STD: vector <touch *> & touches, event * unused_event) {} void gamescene: ontouchescancelled (const STD: vector <touch *> & touches, event * unused_event ){}
Remarks: Master the traversal of the members in the touches container.