Shani Rosen
Shani Rosen

Reputation: 51

Changing background in Swift SpriteKit score based

I'm trying to build a game (Swift Sprite Kit) in which the background of the scene will change immediately after the user has passed a certain number of scores. This is not working (in GameScene)

func addSwitchBackgrounds() {

         let pointsLable = MLPointsLabel(num: 0)

        if (pointsLable == 30) {

            let backgroundTexture = SKTexture (imageNamed: "Store")
            let backgroundImage =  SKSpriteNode (texture: backgroundTexture,size:view!.frame.size)
            backgroundImage.position = view!.center

        } 
}

can anyone help?

Upvotes: 2

Views: 575

Answers (1)

Whirlwind
Whirlwind

Reputation: 13675

This simple example should point you to the right way (just copy&paste to see how it works)...

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    let backgroundNode = SKSpriteNode(imageNamed: "background")

    var score = 0

    let label = SKLabelNode(fontNamed: "ArialMT")

    override func didMoveToView(view: SKView) {
        //setup scene


        backgroundNode.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))

        label.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))

        label.text = "SCORE : 0"

        self.addChild(backgroundNode)

        self.addChild(label)

    }


    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {


        score++

        if(score == 5){

            self.backgroundNode.texture = SKTexture(imageNamed: "background_v2")



        }
         label.text = "SCORE : \(score)"

    }


}

First, you make a backgroundNode property and then, later on in code you change its texture. You don't have to make constant checks in update method about current score. You can make that check only when score is increased. I am not sure where do you call addSwitchBackgrounds though, but just want you to know, that there is no need to use update: method for this.

Upvotes: 2

Related Questions