FreeFire FreeFire - 1 month ago 5x
iOS Question

Animating Sprite Sheets in Cocos2d

I'm having some issues with animating my sprite sheet. I got this code before and it worked. I had 2 frames and my variable in my loop was only allowed to reach a values of 0 and 1 since the frame names were stickman0-568.png and stickman1-568.png. My frames weren't so good so I made a new sprite sheet with 3 frames in it, stickman0-568.png, stickman1-568.png, and stickman2-568.png. My .list file is called sickman-568.plist and the .png sprite sheet is stickman-568.png. I changed the loop so i could only reach a value of 2(0,1,2). When I run it now, it crashes, despite it working before when I only had 2 frames. Can anyone please give me suggestions as to what might have went wrong? Here's my code so you can see what I did:

-(id) init
if( (self=[super init]) )
backGroundDesert = [CCSprite spriteWithFile:@"DesertMap.png"];
backGroundDesert.position = ccp(backGroundDesert.textureRect.size.width/2, backGroundDesert.textureRect.size.height/2);
[self addChild:backGroundDesert];
[backGroundDesert runAction:[CCMoveBy actionWithDuration:100 position:ccp(-1400,0)]];

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"stickman-568.plist"];
CCSprite *mainGuy = [CCSprite spriteWithSpriteFrameName:@"stickman0-568.png"];
mainGuy.position = ccp(40,backGroundDesert.textureRect.size.height/2);
CCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:@"stickman-568.png"];
[batchNode addChild:mainGuy];
[self addChild:batchNode];
NSMutableArray *animFrames = [NSMutableArray array];
for(int i = 0; i < 3; i++)
CCSpriteFrame *frames = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"stickman%02d-568.png", i]];
[animFrames addObject:frames];
CCAnimation *cape = [CCAnimation animationWithSpriteFrames:animFrames delay:0.2f];
[mainGuy runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:cape restoreOriginalFrame:NO]]];
return self;

[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
[super dealloc];


When You Run the code the for loop create the images as below name


That is not images in your sources so only replace below line in your code of for loop. It work fine.

Change the code as below.

CCSpriteFrame *frames = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"stickman%d-568.png", i]];

See this