jhnj
jhnj

Reputation: 1

add another background image to change background during playing game

func createBackgrounds() {
    for i in 0...2 {
       let bg = SKSpriteNode(imageNamed: "BG Day")
       bg.name = "BG"
       bg.zPosition = 0;
       bg.anchorPoint = CGPoint(x: 0.5, y: 0.5)
       bg.position = CGPoint(x: CGFloat(i) * bg.size.width, y: 0)
       self.addChild(bg)
    }
}

If I want to add another background image after 2 minutes to BG Night, how can I write coding in swift 2?

Upvotes: 0

Views: 91

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

You can use SKAction.runBlock to run some code in the future

class GameScene: SKScene {

    var background: SKSpriteNode?

    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        changeBackgroundIn2Mintues()
        self.background = SKSpriteNode(imageNamed: "OLD_BG_IMAGE_NAME")
    }

    private func changeBackgroundIn2Mintues() {

        let wait = SKAction.waitForDuration(60 * 2)
        let changeBG = SKAction.runBlock { [unowned self] in
            self.background?.removeFromParent()
            self.background = SKSpriteNode(imageNamed: "NEW_BG_IMAGE_NAME")
        }
        let sequence = SKAction.sequence([wait, changeBG])
        self.runAction(sequence)

    }
}

Upvotes: 1

Westside
Westside

Reputation: 685

You can do this simply by animating a UIImage. As follows:

let bgImageArray = [UIImage(named: "BG Day")!, UIImage(named: "BG Night")!]

bg.animationImages = bgImageArray
bg.animationDuration = 120 //seconds
bg.animationRepeatCount = 0 //forever
bg.startAnimating()

Then just put the image bg at the back of your view.

Upvotes: 0

Related Questions