01219245/cocos2d/Actions
- This is part of 01219245.
In this short tutorial, we shall not create a new game, but we will learn a few useful techniques for making our game more engaging.
Actions
Using a combination of states and update method is very useful when we want to (micro) manage our objects. However, sometimes, we just want to tell object to do something like jumping or falling and do not want to keep track of these action.
For example, when our flappy dot dies, we want it to fall down to the ground. If we use states, we might want to add code to move the sprite downwards slighly in update method and to keep track that the dot reaches the ground. It will be easier if you can just tell the dot to fall down, and then stop worrying about it as the object shall move accordingly by itself (or by some magics). In Cocos2d-html5, there is a mechanism for performing that kind of work, called actions (See reference here, type action in to the search box). (Read an overview for C++ version in Cocos2d-x here.)
We shall learn how to use actions by examples.
Falling dot
We shall let the player falls. In this case, we use cc.MoveTo (ref) action to tell the object to move to a specific location. After we create the action, we can tell the object to perform an action simply by calling method runAction.
Add method fall to class Player:
fall: function() {
var pos = this.getPosition();
var fallAction = cc.MoveTo.create( 0.5, new cc.Point( pos.x, 0 ) );
this.runAction( fallAction );
}
This action tell the Player to move to the ground (where y co-ordinate = 0) in 0.5 seconds. You can call this method fall at an appropriate location in GameLayer (e.g., after the Player hits the pillars).
Flapping dot: animations and combining actions
We shall make the dot animate. The associated action is cc.Animate (ref), which an be created with cc.Animation (ref). (Note the action is cc.Animate, the animation data is created in cc.Animation object.)