2013-10-13 97 views
1

在我的iOS遊戲中,我希望英雄能夠持續運行,直到屏幕被觸及,英雄跳躍。所以我寫:
在.h文件中:cocos2d sprite永遠重複動畫

@interface Hero : CCSprite { 
    CCSprite *_hero; 
    id _keepRunning; 
} 
@property(nonatomic,retain) id keepRunning; 

在.m文件:

@synthesize keepRunning = _keepRunning; 
-(id) init { 
    _keepRunning = [CCRepeatForever actionWithAction:[CCAnimate actionWithSpriteSequence:@"heroRun%04d.png" 
                       numFrames:30 
                        delay:0.02f 
                    restoreOriginalFrame:NO]];   
} 

隨後的比賽開始時,我調用run()方法:

-(void) run { 
    [_hero stopAllActions]; 
    [_hero runAction:_keepRunning]; 
    _heroState = RUNNING; 
} 

然後我發現CCAnimate actionWithSpriteSequence: numFrames: delay: restoreOriginalFrame:已在cocos2d v2.0中棄用。所以我的問題是,在cocos2d v2.0中,我如何實現這個動畫?也就是說,讓我的英雄跑?謝謝!
編輯:
我已經試過這樣:

-(CCAnimation*) getMyAnimationWithFramesName:(NSString*)nameFormat numFrames:(int)numFrames delay:(float)delay { 
    NSMutableArray *frames = [[NSMutableArray alloc] init]; 
    for (int i = 1; i <= numFrames; i++) { 
     NSString *frameName = [NSString stringWithFormat:nameFormat,i]; 
     [frames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:frameName]]; 
    } 
    CCAnimation *ani = [CCAnimation animationWithSpriteFrames:frames delay:delay]; 
    return ani; 
} 

然後到了init():

_keepRunning = [self getMyAnimationWithFramesName:@"heroRun%04d.png" numFrames:30 delay:0.02f]; 

和運行():

[_hero runAction:[CCAnimate actionWithAnimation:_keepRunning]]; 

但它仍然不工作。我該怎麼辦?

+0

嘗試更大的延遲(即0.1)。嘗試記錄幀名稱和/或幀數組以驗證名稱是否正確。另外,如果您不使用ARC,則會漏出幀數組。 – LearnCocos2D

+0

@ LearnCocos2D我檢查並發現我沒有使用ARC。泄漏幀數組的原因是什麼?如何糾正?謝謝! – lkkeepmoving

+0

泄漏位於'getMyAnimationWithFramesName:numFrames:delay:'方法的第一行。你不銷燬任何地方創建的數組''' – Morion

回答

2

首先從「http://www.codeandweb.com/texturepacker/download」 下載紋理,使P列表,並使用它下面的代碼

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"AnimatedMan.plist"]; 

CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"AnimatedMan.png"]; 

[self addChild:spriteSheet]; 

收集幀列表(精靈)

NSMutableArray *walkAnimFrames = [NSMutableArray array]; 
for (int i=1; i<=6; i++) { 
    [walkAnimFrames addObject: 
    [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: 
     [NSString stringWithFormat:@"step0%d.png",i]]]; 
} 

給行動到雪碧

CCAnimation *walkAnim = [CCAnimation animationWithSpriteFrames:walkAnimFrames delay:0.1f]; 

     manSprite=[CCSprite spriteWithSpriteFrameName:@"step01.png"]; 
     manSprite.position=ccp(winsize.width/2, winsize.height/2-40); 

Sprite RepeaetForever for manSprite

id first=[CCSequence actions:[CCRepeatForever actionWithAction: 
             [CCAnimate actionWithAnimation:walkAnim]],nil]; 

[manSprite runAction:first];