I have created a number of CCSprites using spriteWithFile.
How do I change the image for the sprite during runtime?
I need to change a few sprites images qui
Try using atlassed textures for you game because you are using same sprite that too with many instances
Use
CCSpriteFrameCache, CCSpriteBatchNode
So you can optimize the texture cache with even more different textures atlassed in a single texture. And all are batched in a single node. This reduces the number of draw calls too and increases frame rate.
Try using
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Characters.plist"];
CCSpriteBatchNode* batch = [CCSpriteBatchNode batchNodeWithFile:@"Characters.png" capacity:10];
[self addChild:batch];
CCSprite* player1 = [CCSprite spriteWithSpriteFrameName:@"Luce.png"];
player1.position = ccp(winSize.width * 0.2, winSize.height * 0.8);
[batch addChild:player1];
and use
CCSprite* player = nil;
CCARRAY_FOREACH(batch.children, player1) {
// some computational code and condition
if (sonecondition) {
[player1 setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"spriteframename.png"]];
}
}
in update or in other parts of code
Use Zwoptex
TexturePacker to create 2D texture atlasses
Hope this helps
Good luck
You just need to change the texture of your CCSprite at runtime like this.
[aSprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"NewImage.png"]];
CCTexture *tex = [CCTexture textureWithFile:fileName];
self.texture = tex;
i code cocos2D-x in c++ : when you use spriteSheet instead of using single file, you shoud use this method. suppose you add your spriteSheet in main layer.
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("sprite_sheet.plist");
_gameBatchNode = CCSpriteBatchNode::create("sprite_sheet.png", 200);
this->addChild(_gameBatchNode, kMiddleground);
kMiddleground is just a defined integer.
then i want to change picture of a sprite that already has a sprite with name "cloud.png" i use this code to do that:
cloud->setDisplayFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("blackCloud.png") );
If you are using SpriteSheets, this will work.
NSString* newSprite = [NSString stringWithString:@"SPRITE_NAME.png"];
CCSpriteFrameCache* cache = [CCSpriteFrameCache sharedSpriteFrameCache];
[sprite setDisplayFrame:[cache spriteFrameByName:newSprite]];
[yourSprite setTexture:[[CCSprite spriteWithFile:@"yourImage.png"]texture]];