精灵是游戏的主角,我们在游戏中经常看到各种炫丽的精灵动画效果,之前我们提到精灵是由图片生成的,如果我们想要实现精灵的动画效果,比如捕鱼达人中摇尾游戏动的小鱼,就需要我们用很多张图片来生成一个个纹理,然后使纹理生成一个个的帧,再将这一个个的帧生成一个动画,额,说得有点乱,看代码会比较明白;
首先自定义一个精灵类fishSprite
fishSprite.h
#import #import "cocos2d.h"@interface fishSprite : CCSprite { }+(id)fish;@end
fishSprite.m
@implementation fishSprite
+(id)fish
{
return [[self alloc]initWithImage];
}
-(id)initWithImage
{
if ((self=[super initWithFile:@"fish1.png"])) {
NSMutableArray* frames = [NSMutableArray arrayWithCapacity:18];
//生成一个18的Array;
for (int i = 1; i < 19; i++)
{
NSString *pngFile = [NSString stringWithFormat:@"fish%d.png",i];
//利用已知图片名生成纹理;
CCTexture2D *texture = [[CCTextureCache sharedTextureCache]addImage:pngFile];
//利用纹理生成组成动画的帧;
CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:texture rect:CGRectMake(0, 0, texture.contentSize.width, texture.contentSize.height)];
//将生成的帧添加到数组中,共18个,之后我们要用这18个frame来构成动画;
[frames addObject:frame];
}
//利用帧数组生成一个动画,设定帧与帧之间的切换频率为0.05;
CCAnimation *animation =[CCAnimation animationWithSpriteFrames:frames delay:0.05];
//用CCAnimate将生成的CCAnimation转成可以用精灵操作的动作action:
CCAnimate *animate = [CCAnimate actionWithAnimation:animation];
//设置为repeat
CCRepeatForever *repeat = [CCRepeatForever actionWithAction:animate];
//执行
[self runAction:repeat];
//这样,如果该精灵一被实例化成功,就会动起来;
}
return self;
}
@end
修改模板自动生成的IntroLayer
IntroLayer.h
#import "cocos2d.h"
#import "fishSprite.h"
// HelloWorldLayer
@interface IntroLayer : CCLayer
{
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
@end
IntroLayer.m
#import "IntroLayer.h"
#pragma mark - IntroLayer
// HelloWorldLayer implementation
@implementation IntroLayer
// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
IntroLayer *layer = [IntroLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
//
-(void) onEnter//在载入该节点时被调用,有可能被调有多次;
{
[super onEnter];
// ask director for the window size
CGSize size = [[CCDirector sharedDirector] winSize];
CCSprite *background;
background = [CCSprite spriteWithFile:@"bg.jpg"];
background.position = ccp(size.width/2, size.height/2);
// add the label as a child to this Layer
[self addChild: background];
//在层上添加精灵;
fishSprite *fish = [fishSprite fish];
fish.position = ccp(160,120);
[self addChild:fish];
}
@end
至于自动生成的helloWorld类直接删掉,这里不用它;另外,我们在工程里还需要添加组成帧动画的一个一个图片,如图所示;
这样运行后就可以看到一个不停运动的精灵,该精灵被创建后就是一个不断运动的效果,只需要指定位置,就会在指定的位置显示(图片不显示动画,懒得做gif了,亲们理解下啊),最后大家自己看下代码自己实现下,很简单的;