我遇到了一个奇怪的 Cocos2d 动画问题。
如果我的 createAndRunAnimationonSprite 方法被调用,则在初始化时效果很好。
但是,如果我等待并使用方法 showSprite 将其分配给按钮,则精灵永远不会出现。我不知道为什么会发生这种行为。我没有其他方法或类。
HelloWorldLayer.h
@interface AnimationViewerLayer : CCLayer
{
CCSprite *sprite;
}
HelloWorldLayer.m
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {
CGSize winSize = [[CCDirector sharedDirector] winSize];
// initialize the sprite
sprite = [CCSprite node];
sprite.position = ccp( winSize.width/2 , winSize.height/2 );
[self addChild: sprite];
// If this is uncommented the sprite will show up.
// [self createAndRunAnimationOnSprite];
}
return self;
}
- (void) showSprite {
[self createAndRunAnimationOnSprite];
}
-(void) createAndRunAnimationOnSprite {
// stop all previous ones
[sprite stopAllActions];
NSLog(@"Create and Run Animation");
CGSize winSize = [CCDirector sharedDirector].winSize;
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"ThisSprite.plist"];
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"ThisSprite.png"];
[self addChild:spriteSheet];
NSMutableArray *aniFrames = [NSMutableArray array];
for(int i = 1; i <= 3; ++i) {
[aniFrames addObject: [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [NSString stringWithFormat:@"ThisSprite_walking_%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:aniFrames delay:0.1f];
sprite = [CCSprite spriteWithSpriteFrameName:@"ThisSprite_walking_1.png"];
sprite.position = ccp(winSize.width/2, winSize.height/2);
id walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
[sprite runAction:walkAction];
[spriteSheet addChild:sprite];
}