在玩游戏时添加另一个背景图像来改变背景

时间:2016-07-19 03:02:10

标签: ios swift sprite-kit

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)
    }
}

如果我想在2分钟后添加另一张背景图片到BG Night,我怎样才能在swift 2中编写代码?

2 个答案:

答案 0 :(得分:1)

您可以使用SKAction.runBlock来运行某些代码

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)

    }
}

答案 1 :(得分:0)

您只需动画UIImage即可。如下:

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

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

然后只需将图片bg放在视图的背面即可。