ENDLESS無限循環(huán)背景1.png
紅色框中的節(jié)點(diǎn)bgNode1,SpriteNode的名稱Name BG1 位置為Position(0,0)
bgNode1 = childNode(withName: "BG1") as! SKSpriteNode
黃色框?yàn)榈墓?jié)點(diǎn)bgNode2, SpriteNode的名稱Name BG2 位置為Position(0,2048)
bgNode2 = childNode(withName: "BG2") as! SKSpriteNode
二個(gè)SpriteNode同時(shí)向下移動(dòng)
func updateBackground(deltaTime:TimeInterval){
// 下移
bgNode1.position.y -= CGFloat(deltaTime * 300)
bgNode2.position.y -= CGFloat(deltaTime * 300)
}
override func update(_ currentTime: TimeInterval) {
// 每Frame的時(shí)間差
if lastUpdateTimeInterval == 0 {
lastUpdateTimeInterval = currentTime
}
deltaTime = currentTime - lastUpdateTimeInterval
lastUpdateTimeInterval = currentTime
// endless 無限循環(huán)星空背景
updateBackground(deltaTime: deltaTime)
}
ENDLESS無限循環(huán)背景2.png
當(dāng)紅色框BG1的位置bgNode1.position.y < bgNode1.size.height 的高度(即屏幕的height),把bgNode1
移到之間黃色框的位置
// 第一個(gè)背景node
if bgNode1.position.y < -bgNode1.size.height {
bgNode1.position.y = bgNode2.position.y + bgNode2.size.height
}
ENDLESS無限循環(huán)背景3.png
此時(shí)黃色框bgNode2.position.y = 0 位于屏幕的正中央
紅色框bgNode1.position.y = 2048 取代之間花黃色框的位置,同理,黃色框再次向下移動(dòng)時(shí)惶我,當(dāng)黃色框BG2的位置bgNode2.position.y < bgNode2.size.height 的高度(即屏幕的height),把bgNode2
移到之間當(dāng)前紅色框(bgNode1)的位置戳晌,代碼如下
// 第二個(gè)背景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的時(shí)間差
if lastUpdateTimeInterval == 0 {
lastUpdateTimeInterval = currentTime
}
deltaTime = currentTime - lastUpdateTimeInterval
lastUpdateTimeInterval = currentTime
// endless 無限循環(huán)星空背景
updateBackground(deltaTime: deltaTime)
}
func updateBackground(deltaTime:TimeInterval){
// 下移
bgNode1.position.y -= CGFloat(deltaTime * 300)
bgNode2.position.y -= CGFloat(deltaTime * 300)
// 第一個(gè)背景node
if bgNode1.position.y < -bgNode1.size.height {
bgNode1.position.y = bgNode2.position.y + bgNode2.size.height
}
// 第二個(gè)背景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