Cocos2D-x Tutorials Part 3: Moving a Sprite

In Part 1 and Part 2 we learned to add our layer and sprite.
In this tutorial we will move our sprite where we touched on the screen. Or more generally speaking we will see how to apply an Action on a sprite. Also we will take a look at the touch event.

So lets begin with cocos2d-x Action, for this tutorial the action will be MoveTo.
What does an Action mean ??? well, its simple, it means to do something with a sprite or in a broader sense do something with a node (Sprite is a cocos2d-x Node object). You can Rotate a sprite, you can move it, you can jump it, skew it …… and what not !!!

In this tutorial we will do something like this: we will touch somewhere on our screen and our sprite will move to that particular location.

Lets add the code at our cpp file. we dont need any change in our header file from the last tutorial.

cocos2d-x has 3 types of Touch Events :

  1. on Touch began ( returns bool) / on Touches began (returns void)
  2. on Touch Moved (returns void) / on Touches Moved (returns void)
  3. on Touch Ended (returns void) / on Touches Ended (returns void)

We will use onTouchesEnded for this tutorial, that means our sprite will be moved to the location we touched after we put our finger off the screen.

At line 26 we created a event listener so that cocos2d-x process our touches.

At line 27 we used c++11 Lambda function. If you are not familiar with lambda yet, please google it. Its a major feature of c++11.

At line 28 we hold our touch to a touch object. This is similar to CCTouch* touch = Touches -> anyObject() of the previous versions of cocos2d-x.

At line 29 we are converting our touch location to OpenGL location. Remember that at ios UIKit screen coordinates begin from top-left corner where openGL coordinates begin from bottom-left corner. Thats why we need to convert our screen touch location to openGL location.

Line 31 creates a MoveTo action. This action will take 1 sec to complete and will move the sprite where on screen we touched.
Line 32 we tell our cloud sprite to run the MoveTo action.

Now we need to dispatch our event listener and bind it to our cloud sprite. We did that in Line 36 and we are done for now !

Lets run the code and see if we can move the sprite.

Capture3

Looks like we did !!

Next we will dig into some more actions and will see difference between MoveTo / XXXTo and MoveBy / XXXBy actions.

 
205
Kudos
 
205
Kudos

Now read this

Cocos2D-x Tutorials Part 5: Schedule update and Actions Pause and Resume

In the previous tutorial we saw how to create actions and run them in single order or sequentially. In this tutorial we will see how to schedule a function that will be called on every frame and how can we pause and resume the whole... Continue →