holydancer原創,如需轉載,請在顯要位置註明:
轉自holydancer的CSDN專欄,專欄地址:http://blog.csdn.net/holydancer
在之前的文章七,我們自定義了一個精靈類,該精靈類的init初始化方法中我們使其生成一個動畫,並repeatForever,當時我們並沒有使用文章九介紹的紋理圖冊,而是在項目中添加了十幾張png圖片用作動畫中的每一幀,所以我們在生成動畫的時候會比較複雜,要轉成2D紋理,再循環遍歷添加frame數組,再生成動畫;文章九我們介紹了紋理圖冊,將生成動畫的每一幀的png圖片都放到了同一張大的png中,並有一個plist文件來保存每一幀的CGRect範圍等信息,所以我們就不再需要那麼麻煩的方式了,cocos2d中有很好的封裝類來進行這種操作;
下面來看代碼 fishSprite.h:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface fishSprite : CCSprite {
}
+(id)fish;
@end
fishSprite.m:
#import "fishSprite.h"
@implementation fishSprite
+(id)fish
{
return [[self alloc]initWithImage];
}
-(id)initWithImage
{
if ((self=[super init])) {
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"fish.plist"];
// 將所有fish.plist相關的精靈添加到緩存裏;
NSMutableArray *frameArray = [NSMutableArray array];
for (int i = 1; i<15; i++) {
[frameArray addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache ]spriteFrameByName:
[NSString stringWithFormat:@"fish%d.png",i]]];
}
//將幀添加到數組裏,用該數組生成動畫;
CCAnimation *fishAnimation = [CCAnimation animationWithSpriteFrames:frameArray delay:0.05f];
CCAnimate *animate = [CCAnimate actionWithAnimation:fishAnimation];
[self runAction:[CCRepeatForever actionWithAction:animate]];
// 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
在fishSprite.m中,下面註釋的代碼是之前我們沒有使用紋理圖冊時一個紋理一個紋理添加的代碼,另外需要注意的是,昨天我做紋理圖冊的時候沒有注意,只添加了15張圖片,完整的是18張,所以for循環中的個數大家知道就行了,紋理圖冊的循環次數是和plist裏面添加的紋理圖片的個數相對應的;
這樣將fishSprite定義好後,我們在圖層上添加時,只需要如下這樣調用就能創建一個可以不停動畫的精靈;
//在層上添加精靈;
fishSprite *fish = [fishSprite fish];
fish.position = ccp(160,120);
[self addChild:fish];
這只是紋理圖冊的一個簡單的應用,更常見的是我們將其與CCSpriteBatchNode相結合,使圖形的繪製更有效率,我們下次再介紹;