Game Development Reference
In-Depth Information
for (int i = 0; i < 5; i++)
// Create a texture for the animation frame
NSString* file = [NSString stringWithFormat:@"ship-anim%i.png", i];
CCTexture2D* texture = [[CCTextureCache sharedTextureCache] addImage:file];
// The whole image should be used as the animation frame
CGSize texSize = texture.contentSize;
CGRect texRect = CGRectMake(0, 0, texSize.width, texSize.height);
// Create a sprite frame from the texture
CCSpriteFrame* frame = [CCSpriteFrame frameWithTexture:texture rect:texRect];
[frames addObject:frame];
// Create an animation object from all the sprite animation frames
CCAnimation* anim = [CCAnimation animationWithSpriteFrames:frames delay:0.08f];
// Run the animation by using the CCAnimate action and loop it with CCRepeatForever
CCAnimate* animate = [CCAnimate actionWithAnimation:anim];
CCRepeatForever* repeat = [CCRepeatForever actionWithAction:animate];
[self runAction:repeat];
All that just to create a sprite animation with five frames? I'm afraid so. I'll walk you
through the code backward this time, which may explain the setup better. At the very
end you're using a CCAnimate action to play an animation. In this case, you're also
using a CCRepeatForever action to loop the animation.
The CCAnimate action uses a CCAnimation object (which is a container for anim-
ation frames) that defines the delay between each individual frame. In many cases,
you'll later want to refer to a previously created animation. For that purpose, cocos2d
has a CCAnimationCache class that stores CCAnimation instances by name, as
shown in Listing 6-12 . Using the CCAnimationCache , you can access a particular
animation by name later.
Listing 6-12. The CCAnimationCache Class Can Store Animations for You, Which Can
Be Retrieved by Name
Search Nedrilad ::

Custom Search