2

我正在使用 Swift 和 SpriteKit 开发游戏。我希望背景以一定的分数发生变化。这是代码:

 class GameScene: SKScene {
 var bg = SKSpriteNode()

override func didMoveToView(view: SKView) {

   makeBg()
}

func makeBg() {

    let bgTexture = SKTexture(imageNamed: "img/bg.png")
    let moveBg = SKAction.moveByX(-bgTexture.size().width, y: 0, duration: 9)
    let replaceBg = SKAction.moveByX(bgTexture.size().width, y: 0, duration:0)
    let animateBg = SKAction.repeatActionForever(SKAction.sequence([moveBg,   replaceBg]))


    for var i: CGFloat = 0; i<3; i++ {
        let bg = SKSpriteNode(texture: bgTexture)
        bg.name = "background"
        bg.position = CGPoint(x: bgTexture.size().width/2 + bgTexture.size().width * i, y: CGRectGetMidY(self.frame))
        bg.size.height = self.frame.height
        bg.runAction(animateBg)
        addChild(bg)
    }
}     
   override func touchesBegan(touches: Set<UITouch>, withEvent event:    UIEvent?) {
     if score == 0 {
               bg.texture = SKTexture(imageNamed: "img/bg.png")
            } else if score == 3 {
                bg.texture = SKTexture(imageNamed: "img/bgOri.png")
                }
 }

但是图像没有改变......错误在哪里?

4

1 回答 1

2

因此,您可以通过以下方式更改 for 循环内创建的所有节点上的纹理:

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
       makeBg()
    }

    func makeBg() {
        let bgTexture = SKTexture(imageNamed: "img/bg.png")
        let moveBg = SKAction.moveByX(-bgTexture.size().width, y: 0, duration: 9)
        let replaceBg = SKAction.moveByX(bgTexture.size().width, y: 0, duration:0)
        let animateBg = SKAction.repeatActionForever(SKAction.sequence([moveBg,   replaceBg]))

        for var i: CGFloat = 0; i<3; i++ {
            let bg = SKSpriteNode(texture: bgTexture)
            bg.name = "background"
            bg.position = CGPoint(x: bgTexture.size().width/2 + bgTexture.size().width * i, y: CGRectGetMidY(self.frame))
            bg.size.height = self.frame.height
            bg.runAction(animateBg)

            addChild(bg)
        }
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        enumerateChildNodesWithName("background", usingBlock: { node, stop in
            //Make a check based on score and
            (node as? SKSpriteNode)?.texture = //set the right texture
        })
    }
}

请注意,您不需要在 GameScene 中定义 bg 属性来完成此操作。

于 2016-03-05T16:11:03.233 回答