分类: cocos2d |
首先用zwoptex(http://zwoptexapp.com/flashversion/)创建animation.png和animation.plist,两个文件必须同名,使用时不要添加完全空白的图片,不然无法导出png文件。然后将两个文件添加到project里。plist文件存储的是png文件中每个图元的对应坐标和名称(仍然是原文件名)。
播放动画代码如下:
- (void) playAnimation {
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"animation.plist"];
CCSpriteSheet *sheet = [CCSpriteSheet spriteSheetWithFile:@"animation.png"];
CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"Target1.png"];
sprite.position = monster.position; //设置动画播放位置
[self addChild:sheet z:1 tag:100]; //设置tag为了在后面的函数中读取sheet
[sheet addChild:sprite];
NSMutableArray *animationFrames = [NSMutableArray array];//存储动画序列
for(int i = 1; i != 18; i++){
NSString *frameName = [NSString stringWithFormat:@"Target%d.png",i];
CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:frameName];
[animationFrames addObject:frame];
}
CCAnimation *animation = [CCAnimation animationWithName:@"monster dead" delay:0.04f frames:animationFrames];
[sprite runAction:[CCSequence actions:
[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO],
[CCCallFunc actionWithTarget:self selector:@selector(removeAnimation)],nil]];
}
// 添加一个清除函数是因为动画的最后一帧不会消失,如果有更好的处理办法,给我留言
- (void) removeAnimation {
CCSpriteSheet *sheet = (CCSpriteSheet *)[self getChildByTag:100];
[self removeChild:sheet cleanup:YES];
}
cocos2d文档中说道
The sprite frames will be cached AND RETAINED, and they won't be released unless you call // [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
但是我在自己的程序中得出的是sprites frames没有保留(retain),所以在dealloc中添加上面的代码会出错。如果有知道原因的,给我留言。