Wednesday, April 10, 2019

cocos2d iphone - What is the correct way of changing image of existing CCSprite?


How do I correctly change sprite to show another image? Or to have another texture? This is the way I do it now. When I need to change sprite image I increase state variable. So i have one picture for 0, another for 1 and another for 2. First i tried just saying mysprite = [CCSpriteWithFile:@"sprite.png"] but that didn't end up too well since I was making new objects every frame and it got messy pretty fast. So I added a check. There is another variable that is stateChanged and it starts at zero. So I compare state to stateChanged before actually making any sprites and if it differs I do the magic. But here comes the problem. Somehow this sprite won't flip. And I believe the problem is in this method.


- (void) updateState
{
if (stateChanged != state) {

if (state == 0)
{
currentSprite = [CCSprite spriteWithFile:@"eggclosed.png"];

[self addChild:currentSprite];
}

if (state == 1)

{
currentSprite = nil;
[self removeAllChildrenWithCleanup:YES];
currentSprite = [CCSprite spriteWithFile:@"eggopen.png"];
[self addChild:currentSprite];

}

if (state == 2)
{
currentSprite = nil;
[self removeAllChildrenWithCleanup:YES];
currentSprite = [CCSprite spriteWithFile:@"yoshi.png"];
[self addChild:currentSprite];
}


stateChanged = state;
}
}

TLDR: How to correctly change image of sprite. I have a Pet object that has a CCSprite property. And I sometimes need to change sprte to look another way. How do?



Answer



CCTexture2D* tex = [[CCTextureCache sharedTextureCache] addImage:@"new_image_name"];
[spriteWant2Change setTexture: tex];

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...