下面来看代码 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,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];总结
以上是内存溢出为你收集整理的Cocos2d 使用纹理图册,更方便生成精灵动画全部内容,希望文章能够帮你解决Cocos2d 使用纹理图册,更方便生成精灵动画所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)