Feindpak
Feindpak

Reputation: 45

Swift: Change the texture of a Sprite Kit object

how can i change the texture of a SpriteKit object if a variable changes their value.

Something like:

    var x = 2
    if x == 1 {sprite has texture1}
    else if x == 2 {sprite has texture2}

Upvotes: 1

Views: 633

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

If x is a property then you can use a property observer like this

class Hero: SKSpriteNode {

    var x: Int = 1 {
        didSet {
            switch x {
            case 1: self.texture = SKTexture(imageNamed: "texture1")
            case 2: self.texture = SKTexture(imageNamed: "texture2")
            default: break
            }
        }
    }
}

Upvotes: 3

crashoverride777
crashoverride777

Reputation: 10674

Something like this should work

if x == 1 {
    sprite.texture = SKTexture(imageNamed: "Image1")
} else if x == 2 {
    sprite.texture = SKTexture(imageNamed: "Image2")
} 

Hope this helps

Upvotes: 2

Related Questions