你绝对应该继承 CCSprite 来做到这一点。
让我们称它为 alienHominid 类,在您的头文件中,该类可能看起来像这样:
@interface alienHominid : CCSprite {
//helps you find which current frame is being displayed at any moment
int currentFrame;
CCAnimation *flip;
}
//Extra some extra params you might need ?
@property (readwrite) NSNumber *health;
//And your new init method
-(id)initWithSpriteSheet:(NSString*)aSpriteFrame andBatchNode:(NSString*)aBatchNode;
//Some other methods to animate and give it your required behaviours
-(void)startAnimations;
-(void)prepareAnimations;
-(void)stopAnimations;
-(void)removeFromLayer;
@end
现在让我们看看你的实现文件
@implementation alienHominid
//Synth. properties you created here , if any.
@synthesize health = _health;
-(id)initWithSpriteSheet:(NSString*)aSpriteFrame andBatchNode:(NSString*)aBatchNode
{
self = [super init];
if(self)
{
//custom init code
[self setHealth:[NSNumber numberWithInt:100]];
//
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:aSpriteFrame];
alienSheet = [CCSpriteBatchNode batchNodeWithFile:aBatchNode];
}
return self;
}
//Some other methods to animate and give it your required behaviours
-(void)prepareAnimations{
alienFrames = [NSMutableArray array];
for (int i=1; i <= 5; i++) {
[alienFrames addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [NSString stringWithFormat:@"AlienHominid %d.png", i]]];
if (i==5)
[alienFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:@"AlienHominid 1.png"]];
}
CCAnimation *alienAnim = [CCAnimation animationWithSpriteFrames:alienFrames delay:0.1];
flip = [[CCRepeatForever alloc ] initWithAction:[CCAnimate actionWithAnimation:alienAnim]];
}
-(void)startAnimations{
[flip start];
}
-(void)stopAnimations{
//Stop animations here
[flip stop];
}
-(void)removeFromLayer{
//If alien dies, remove it here
}
@end
现在您可以通过导入它的标题轻松地在任何场景中使用它
#import "alienHominid.h"
并像这样添加它:
alienHominid *alien = [[alienHominid alloc] initWithSpriteSheet:@"AlienHominid-ipadhd.plist" andBatchNode:@"AlienHominid-ipadhd.png"];
[alien prepareAnimations];
[alien startAnimations];
[self addChild:alien];
注意此代码未经测试,只是将我想到的内容写入浏览器,因此希望它不起作用,但它应该让您对我要传达的内容有一个简单的了解:),甚至将其视为伪代码如果它有效;)
干杯!