How to switch CCSprite image

I have a CCSprite that is initialized with [CCSprite spriteWithSpriteFrameName:@"plist_file_key_here.png"] . I already added all the sprites from my plist file to CCSpriteFrameCache. I tried to adjust the texture as follows:

 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 does not work. I think this has something to do with the difference between using [CCSprite spriteWithFile:] and [CCSprite spriteWithSpriteFrameName:] , which relies on sprite frames loaded into CCSpriteFrameCache from the 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 a way around this or do I need to delete and recreate the sprite? If this is my only option, is there a way to remove ccnode from its parent, but save its children?

+6
source share
3 answers

API Rescue Link!

When you have a texture with a sprite frame, you do not want to change the texture, but a sprite frame that uses a sprite. This can be done as follows:

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

in cocos2d v3 it should be:

 sprite.spriteFrame = frame; 
+17
source

To change a CCSprite image 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]]; 
+3
source

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 mySprite to myNewImage.png

Note. If the image you want to change is located in any particular asset folder, you can evaluate this image using the entire image path.

0
source

Source: https://habr.com/ru/post/901859/


All Articles