6

I have a CCSprite that is initialized using [CCSprite spriteWithSpriteFrameName:@"plist_file_key_here.png"]. I have already added all the sprites from my plist file to CCSpriteFrameCache. I have tried setting the texture like this:

CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:name];
NSAssert(frame.texture!=nil, @"frame.texture can't equal nil"); //this works fine
[sprite setTexture:frame.texture]; //doesn't cause a white square to appear, just doesn't switch the image.

As I said in my comments, this doesn't work. I think it has something to do with the difference between using [CCSprite spriteWithFile:] and [CCSprite spriteWithSpriteFrameName:], which relies on sprite frames loaded into the CCSpriteFrameCache from a texture atlas. When using sprites loaded from a texture atlas, the texture of each sprite is equal to the texture of the sprite sheet. Is there any way around this or do I have to remove and recreate the sprite? If that is my only option, is there a way of removing a ccnode from its parent but preserving its children?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Ben Trapani
  • 271
  • 1
  • 4
  • 11

3 Answers3

17

The API Reference to rescue!

When you have a texture with sprite frame, you don't want to change the texture but the sprite frame the sprite uses. That you can do as follows:

CCSpriteFrameCache* cache = [CCSpriteFrameCache sharedSpriteFrameCache];
CCSpriteFrame* frame = [cache spriteFrameByName:name];
sprite.displayFrame = frame;

in cocos2d v3 it would need to be:

sprite.spriteFrame = frame;
CodeSmile
  • 64,284
  • 20
  • 132
  • 217
3

To change the image of a CCSprite as an animation with 1 second between each frame:

CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];

CCSpriteFrame *frame1 = [cache spriteFrameByName:[NSString stringWithFormat:@"plist_file_key_here1.png"]];               
CCSpriteFrame *frame2 = [cache spriteFrameByName:[NSString stringWithFormat:@"plist_file_key_here2.png"]];             

NSArray *animFrames = [NSArray arrayWithObjects:frame1, frame2, nil];

CCAnimation *animation = [CCAnimation animationWithFrames:animFrames delay:1.0f];
[originalSprite runAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO]];
codeperson
  • 8,050
  • 5
  • 32
  • 51
0

Consider a CCSprite object named mySprite. Now you can change the image of the sprite as follows:

[mySprite setTexture:[[CCTextureCache sharedTextureCache] addImage:[Tools imageNameForName:"myNewImage.png"]]];

This will change the image of the CCSprite object mySprite to myNewImage.png

Note : If the image to be changed is in any particular folder of the assets, then you can assess that image by using the whole path of the image.

cREcker
  • 2,323
  • 1
  • 16
  • 13