iFIERO -- 如何用SpriteKit实现游戏中的ENDLESS无限循环背景



红色框中的节点bgNode1,SpriteNode的名称Name BG1 位置为Position(0,0)

bgNode1 = childNode(withName: "BG1") as! SKSpriteNode

黄色框为的节点bgNode2, SpriteNode的名称Name BG2 位置为Position(0,2048)

bgNode2 = childNode(withName: "BG2") as! SKSpriteNode

二个SpriteNode同时向下移动

    func  updateBackground(deltaTime:TimeInterval){
        // 下移
        bgNode1.position.y -= CGFloat(deltaTime * 300)
        bgNode2.position.y -= CGFloat(deltaTime * 300)     
    }

    override func update(_ currentTime: TimeInterval) {
        // 每Frame的时间差
        if lastUpdateTimeInterval == 0 {
            lastUpdateTimeInterval = currentTime
        }
        deltaTime = currentTime - lastUpdateTimeInterval
        lastUpdateTimeInterval = currentTime
        
        // endless 无限循环星空背景
        updateBackground(deltaTime: deltaTime)
    }

ENDLESS无限循环背景2.png

当红色框BG1的位置bgNode1.position.y < bgNode1.size.height 的高度(即屏幕的height),把bgNode1
移到之间黄色框的位置

// 第一个背景node
        if bgNode1.position.y  < -bgNode1.size.height {
            bgNode1.position.y = bgNode2.position.y + bgNode2.size.height
        }
ENDLESS无限循环背景3.png

此时黄色框bgNode2.position.y = 0 位于屏幕的正中央
红色框bgNode1.position.y = 2048 取代之间花黄色框的位置,同理,黄色框再次向下移动时,当黄色框BG2的位置bgNode2.position.y < bgNode2.size.height 的高度(即屏幕的height),把bgNode2
移到之间当前红色框(bgNode1)的位置,代码如下

// 第二个背景node
        if bgNode2.position.y  < -bgNode2.size.height {
            bgNode2.position.y = bgNode1.position.y + bgNode1.size.height
        }

完整的代码如下:

var lastUpdateTimeInterval:TimeInterval = 0
    var deltaTime:TimeInterval = 0

override func update(_ currentTime: TimeInterval) {
        // 每Frame的时间差
        if lastUpdateTimeInterval == 0 {
            lastUpdateTimeInterval = currentTime
        }
        deltaTime = currentTime - lastUpdateTimeInterval
        lastUpdateTimeInterval = currentTime
        
        // endless 无限循环星空背景
        updateBackground(deltaTime: deltaTime)
    }
    
    func  updateBackground(deltaTime:TimeInterval){
        // 下移
        bgNode1.position.y -= CGFloat(deltaTime * 300)
        bgNode2.position.y -= CGFloat(deltaTime * 300)
        // 第一个背景node
        if bgNode1.position.y  < -bgNode1.size.height {
            bgNode1.position.y = bgNode2.position.y + bgNode2.size.height
        }
        // 第二个背景node
        if bgNode2.position.y  < -bgNode2.size.height {
            bgNode2.position.y = bgNode1.position.y + bgNode1.size.height
        }
        
    }

更多游戏教程:http://www.iFIERO.com
Github游戏代码传送门:https://github.com/apiapia/SpaceBattleSpriteKitGame


猜你喜欢

转载自blog.csdn.net/apiapia/article/details/80770716