user3138007
user3138007

Reputation: 637

Changing sprite Images in Sprite-Kit

Is there a way to change the image of a sprite which has already been initialized with another image?

I tried:

if ([node.name isEqualToString:@"NameX"]) {
        SKAction *fadeOut = [SKAction fadeOutWithDuration:0.3];
        SKAction *fadeIn = [SKAction fadeInWithDuration:0.3];

       [self.sprite runAction:fadeOut];

       [self runAction:fadeOut completion:^{

             self.sprite = [SKSpriteNode spriteNodeWithImageNamed:@"NameY"];

             [self.sprite runAction:fadeIn]

            }];

}

Upvotes: 6

Views: 5440

Answers (2)

erdikanik
erdikanik

Reputation: 744

You must create texture array such as this:

 [SKAction animateWithTextures:[NSArray arrayWithObjects:
                               [SKTexture textureWithImageNamed:@"im1.png"],
                               [SKTexture textureWithImageNamed:@"im2.png"],
                               [SKTexture textureWithImageNamed:@"im3.png"],
                               [SKTexture textureWithImageNamed:@"im4.png"], nil] timePerFrame:0.5 resize:YES restore:YES];

Upvotes: 2

Mick MacCallum
Mick MacCallum

Reputation: 130193

There is. Internally, the spriteNodeWithImageNamed: class method just uses the image name you pass it to set the node's texture property. That being said, if at any point you want to arbitrarily change the node's texture, you can just set it directly.

[self.sprite setTexture:[SKTexture textureWithImageNamed:@"someOtherImage"]];

There are also some SKActions for doing this, in case you want the node to resize or animate between different textures.

[self.sprite runAction:[SKAction setTexture:[SKTexture textureWithImageNamed:@"someOtherImage"] resize:YES]];


[self.sprite runAction:[SKAction animateWithTextures:@[tex1,tex2,tex3] timePerFrame:0.5 resize:YES restore:YES]];

Upvotes: 12

Related Questions