Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch the image of a CCSprite

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?

like image 211
Ben Trapani Avatar asked Nov 18 '11 23:11

Ben Trapani


1 Answers

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;
like image 154
LearnCocos2D Avatar answered Sep 30 '22 07:09

LearnCocos2D