As part of the ongoing development of my current game project (using cocos2d-iphone), I recently found myself facing yet another clone of the code required to animate an object within a scene.
Whilst it’s so easy to just grab code, plonk it in and modify it to suit your purposes, it’s a good idea to stop yourself every now and then and assess the damage.
I was finding that the code was becoming untidy, and it was time to do some refactoring. So, having recognised that all of my animated sprites were essentially being created the same way, I set about creating my CCAnimatedSprite class which is a subclass of CCSprite.
What it does is provide an easy to use constructor (to borrow a Java term) that, given the “name” of the spritesheet that contains the images that make up the animation, sets up the sprite object , all ready to go. From there its very simple to request an action object that can be used on it’s own, or as a part of a more complicated suite of actions.
So, to create an animated sprite, all you need is:<
CCAnimatedSprite *animSprite1 = [CCAnimatedSprite nodeWithSheetName:@"anim" andFrameCount:15];
What this does is create a CCSprite object that contains all the information it needs to animate 15 frames from a spritesheet called “anim_sheet.png”.
So, for this animated sprite there are two files it expects to find:
- “anim_sheet.plist” which is a standard cocos2d spritesheet description file.
- “anim_sheet.png” which is the spritesheet itself.
In additon to this, each frame within the animation is expected to have a name that takes the form:
CCAnimatedSprite *animSprite1 = [CCAnimatedSprite nodeWithSheetName:@"anim"
[animSprite1 setPosition:CGPointMake(300.0, 257.0)];
[self addChild:animSprite1 z:10];
If you need to embed the animation within a suite of actions that have the sprite moving on the screen in some fashion, you can use the “animationAction” method to get a CCAnimate action object:
CCAnimatedSprite *animSprite2 = [CCAnimatedSprite nodeWithSheetName:@"anim"
[animSprite2 setPosition:CGPointMake(20.0, 157.0)];
[self addChild:animSprite2 z:10];
[animSprite2 runAction:[CCRepeatForever actionWithAction:
[CCRepeat actionWithAction:[animSprite2 animationAction] times:6],
[CCMoveTo actionWithDuration:2.5 position:CGPointMake(880.0, 157.0)],
[CCMoveTo actionWithDuration:2.5 position:CGPointMake(20.0, 157.0)],
You can get the code and a very simple sample project from: http://www.pkclsoft.com/downloads/AnimatedSprite.zip