Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change texture on SKSpriteNode

I have an SKSpriteNode and I want to change the texture on it when the user touches the screen. But cannot work out how to do so.

Creating and adding the head. (Declared in header).

    head = [SKSpriteNode spriteNodeWithImageNamed:[NSString stringWithFormat:@"%@",face]];
    head.position = CGPointMake(size.width / 2, size.height / 2);
    [self addChild:head];

When a touch is detected, the below is run, but I cannot work out how to apply it to the SKSpritenode?!

            SKAction* changeFace = [SKAction setTexture:[SKTexture textureWithImageNamed:[NSString stringWithFormat:@"%@",face]]];
            [self runAction:changeFace];

I have tried the below also, but it does not seem to work...

            head.texture = [SKTexture textureWithImageNamed:[NSString stringWithFormat:@"%@",face]];

Hope somebody is able to point me in the correct direction!

like image 986
zipie Avatar asked Oct 27 '13 13:10

zipie


3 Answers

It looks like you are trying to run the action on the scene (or any other object than your sprite.) The second code should work however, but using the SKAction try this instead.

[head runAction:changeFace];
like image 180
Six Foot Three Foot Avatar answered Oct 16 '22 16:10

Six Foot Three Foot


I have it working here, look at the code below:

1 - Create the SKSpriteNode

self.ninja = [SKSpriteNode spriteNodeWithImageNamed:@"ninja1"];
self.ninja.position = CGPointMake(self.ninja.size.width/2, self.frame.size.height/2);
[self addChild:self.ninja];

2 - Change the texture:

self.ninja.texture = [SKTexture textureWithImageNamed:@"ninja2"];

Obs: I change the texture in touchesBegan event, but this should work in any way you want to do.

like image 21
Daniel Lima Avatar answered Oct 16 '22 16:10

Daniel Lima


I also experiencing this one, I was able to change texture but the the texture is stretch. What is causing this?

like image 3
user1969245 Avatar answered Oct 16 '22 16:10

user1969245