Question

I'm using Cocoa2Ds to make a game for iOS. I know it's probably simple, but is there a way to change a CCFile's sprite images programmatically?

I created a hero sprite object and then dragged it into the main scene utilizing SpriteBuilder.

Ultimately, I would like to change the hero sprite object to another image that is animating (moving) as well.

Was it helpful?

Solution

You asked about changing a "CCFile" image, but I assume you meant "CCSprite" image. If so, changing a sprite image can be done by first creating a sprite frame and then assigning it to the sprite:

CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"NameOfFrame"];
[mySprite setDisplayFrame:frame];

For this to work the image you are referencing must already be loaded into memory, such as through a sprite sheet:

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

You mentioned animation. If you are trying to animate a sprite, and all the images are loaded into memory and they have the same name except for a sequential number appended to them, then you can have a sprite move through these images, thus animating it, as follows:

NSString * animateCycle = [NSString stringWithFormat:@"ImageName 00%%02d.png"];

The image names would be along the lines of "ImageName 0001.png", "ImageName 0002.png", and so on.

CCActionInterval * action = [CCAnimate actionWithSpriteSequence:animateCycle numFrames:8 delay:.1 restoreOriginalFrame:YES];
[mySprite runAction:action];

This will cycle through the images based on the designated delay.

I hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top