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.


Looks like we did !!

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


Now read this

Cocos2D-x Tutorials Part 6: Switching between scenes

In this tutorial we are going to see how to create a menu for our game that will let us switch between different game scenes. There are multiple ways to design a menu in cocos2d-x. In the default generated code we can see how to create a... Continue →