3

Is it possible to update/change the image of an SKSpriteNode?
The code below does not work:

var boss1 = SKSpriteNode(imageNamed: "boss1.png")
boss1 = SKSpriteNode(imageNamed: "boss2.png")
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
Glutch
  • 662
  • 1
  • 6
  • 19

2 Answers2

7

Once you created the SKSpriteNode

var boss1 = SKSpriteNode(imageNamed: "boss1.png")

you can update the texture property like that

boss1.texture = SKTexture(imageNamed: "boss2.png")

Here's an example from my Playground

enter image description here

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
4

What you are doing right now is creating a new instance and then use a local variable to reference it. Then, the previous one's retain count will drop to zero and be deallocated. You will have to know what is your intention. Based on the documentation, I think you can change it and the property is texture:

This method creates a new texture object from the image file and assigns that texture to the texture property. The size property of the sprite is set to the dimensions of the image. The color property is set to white (1.0,1.0,1.0).

Here is how you can change it:

boss1.texture = UIImage(...)

Here is the link: https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKSpriteNode_Ref/#//apple_ref/occ/instp/SKSpriteNode/texture

Lucas Huang
  • 3,998
  • 3
  • 20
  • 29