Hassy31
Hassy31

Reputation: 2813

cocos2d change sprite texture

I want to change a sprite texture with another texture from a sprite sheet

//normal sprite
character = [CCSprite spriteWithSpriteFrameName:@"char1.png"];

//change texture
[character setTexture:[[CCTextureCache sharedTextureCache] addImage:[CCSprite spriteWithSpriteFrameName:@"char2.png"]]];

but this gives me an error.I have tried without spriteWithSpriteFrameName and it gives me a blank texture.

//error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CCSprite lastPathComponent]: unrecognized selector sent to instance 0xab32580'

please help me to solve this problem

Upvotes: 2

Views: 3307

Answers (2)

gberginc
gberginc

Reputation: 447

Try setting the displayFrame on the CCSprite, e.g.,

[character setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] 
                        spriteFrameByName:@"char2.png"];

Upvotes: 2

Guru
Guru

Reputation: 22042

AddImage takes input imageName(NSString) not sprite(CCSprite).

[[CCTextureCache sharedTextureCache] addImage:TEX_IMAGE_NAME]; 

Here some useful code for you that solve your crash:

CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"char2.png"];
[crane setTexture:sprite.texture]; //Already allocated memory? if not thn try below
//crane = [CCSprite spriteWithTexture:sprite.texture];
//crane = [CCSprite spriteWithTexture:sprite.texture rect:rect];

Upvotes: 2

Related Questions