Read this tutorial to learn how to set a point for a sprite to move to, and then have the sprite move back.
If you don’t know how to animate a sprite read Animating a Sprite with Cocos2d first.
Begin by downloading the animatingAndMovingASprite code.
Now lets move the sprite. First we need to change repeat from:
Now animate will only repeat 10 times.
Next add the following lines after the id repeat line.
id spawn=[CCSpawn actions:repeat, move,nil];
id move is an action that will last 3 seconds and will move what ever is running the action (in our case it is sprite) to the bottom left corner. CCSpawn will run the action at the same time. So spawn will run repeat and move at the same time.
Now we need to change the runAction from:
This just makes sprite run the spawn action instead.
Ok run the program. You should see your sprite move across the screen. If you notice though the animation continues to run after the move is done. Lets fix that now.
id repeat= [CCRepeat actionWithAction:animate times:timesRepeat];
timesRepeat takes the duration of the move 3 and divides it by the time it takes to play one animation 0.8 seconds (each frame is displayed for 0.4 seconds and we have 2 frames so delay*number of frames = how long it takes to play the animation). I added one to the end because with an integer it cuts of the decimal places so if your animation needs to add one animation loop add one if not leave it off. Then we needed to change repeat to use timesRepeat instead of 10.
Run your code and you should see everything working right.
Now lets move the sprite back.
id spawn2=[CCSpawn actions:repeat, moveBack,nil];
[sprite runAction:[CCSequence actions:spawn,spawn2,nil]];
Ok you have seen most of this before except for CCSequence. CCSequence runs the actions in a sequence one right after the other.
Run again and you will see the sprite go from the top right to the bottom left and back again.
This concludes move a sprite with Cocos2d.
Copy right Britney Lee Johnson August 2010.