How to switch the image of a CCSprite

佐手、 提交于 2019-12-03 14:46:41

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;

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]];

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!