如何在SpriteKit Swift 4中制作垂直无限滚动背景

时间:2018-01-22 05:59:07

标签: ios swift sprite-kit

我需要为我的游戏制作一个背景,从上到下无限滚动。这就是我现在所拥有的,但背景到底但从未回到顶部。这就是我现在所拥有的。我在xcode 9上用swift 4写作。

import SpriteKit

class GameScene: SKScene {
   var ground = SKSpriteNode()

    override func didMove(to view: SKView) {
        createGrounds()
    }

    override func update(_ currentTime: TimeInterval) {
        moveGrounds()
    }

    func createGrounds() { 
        for i in 0 ... 3 {
            let ground = SKSpriteNode(imageNamed: "backGround")
            ground.name = "Ground"
            ground.size = CGSize(width: (self.scene?.size.width)!, height: ((self.scene?.size.height)! * 2))
            ground.anchorPoint = CGPoint(x: 0.5, y:0.5)
            ground.position = CGPoint(x: (CGFloat(i) * ground.size.height), y: (self.frame.size.height / 2))
            self.addChild(ground)
            print(i)
        }
    }

    func moveGrounds() {
        self.enumerateChildNodes(withName: "Ground", using: ({
            (node, error) in

            node.position.y -= 7
            if node.position.y > ((self.scene?.size.height))! {
                node.position.y += (self.scene?.size.height)! / 3
            }
        }))
    }
}

1 个答案:

答案 0 :(得分:0)

一开始,背景位于(self.frame.size.height / 2)高度,每移动一次,您将y减少7,因此y总是小于(self.frame.size.height / 2),你怎么样?认为条件node.position.y > ((self.scene?.size.height))可能是真的吗?

您应该在小于0或类似情况时重置y(取决于您管理anchorposition的方式)。

相关问题