add another background image to change background during playing game

╄→尐↘猪︶ㄣ 提交于 2020-01-07 02:21:21

问题


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?


回答1:


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)

    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/38448908/add-another-background-image-to-change-background-during-playing-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!