How to switch the image of a CCSprite

10,671

Solution 1

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;

Solution 2

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]];
Share:
10,671
Ben Trapani
Author by

Ben Trapani

I am still in high school but am trying to find time to teach myself game development. I have mostly concentrated on ios apps but have programmed some games for PC. I am a decent programmer but am not an artist.

Updated on June 04, 2022

Comments

  • Ben Trapani
    Ben Trapani almost 2 years

    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?