我正在尝试回收相同的SKSpriteNode
以使背景连续。我创建了SKSpriteNode
为bg0
,bg1
,bg2
,并在展示场景时正确放置了它们。不知何故,下面的代码仅重新定位bg0
一次。
cam
是SKCameraNode
,因此,我正在检查相机是否包含背景节点。由于它们的大小,在相机视口中始终不应该显示其中之一。但是,就像我说的那样,这只能使用一次,并且当相机显示回收的bg0
无法识别它时。
谢谢。
PS:我也已经尝试过cam.intersects(bg0)
,得到了相同的结果。
func updateBgPos() {
if (player?.position.y)! > self.frame.height {
if !cam.contains(bg0!) {
print("bg0 is not in the scene")
newPosBgY = (bg2?.position.y)! + self.frame.height
bg0?.physicsBody = nil
bg0?.position = CGPoint(x: self.frame.width / 2, y: newPosBgY)
bg0?.physicsBody = bg1?.physicsBody
} else if !cam.contains(bg1!) {
print("bg1 is not in the scene")
newPosBgY = (bg0?.position.y)! + self.frame.height
bg1?.physicsBody = nil
bg1?.position = CGPoint(x: self.frame.width / 2, y: newPosBgY)
bg1?.physicsBody = bg0?.physicsBody
} else if !cam.contains(bg2!) {
print("bg2 is not in the scene")
newPosBgY = (bg1?.position.y)! + self.frame.height
bg2?.physicsBody = nil
bg2?.position = CGPoint(x: self.frame.width / 2, y: newPosBgY)
bg2?.physicsBody = bg1?.physicsBody
}
}
}
答案 0 :(得分:1)
嗯,终于我弄清楚了如何实现这一目标。我希望这对其他人有帮助。
我最初创建并放置两个SKSpriteNode
作为背景bg0
和bg1
,如下所示:
bg0 = SKSpriteNode(imageNamed: "bg0")
bg1 = SKSpriteNode(imageNamed: "bg1")
bg0!.name = "bg0"
bg1!.name = "bg1"
bg0?.scale(to: CGSize(width: sceneWidth, height: sceneHeight))
bg1?.scale(to: CGSize(width: sceneWidth, height: sceneHeight))
bg0?.zPosition = zPosBg
bg1?.zPosition = zPosBg
backgroundArr.append(bg0!)
backgroundArr.append(bg1!)
bg0?.position = CGPoint(x: sceneWidth / 2, y: 0)
bg1?.position = CGPoint(x: sceneWidth / 2, y: sceneHeight)
self.addChild(bg0!)
self.addChild(bg1!)
之后,在update
方法上,我调用了以下函数:
func updateBgPos() {
guard let playerPosY = player?.position.y else { return }
guard let bg0PosY = bg0?.position.y else { return }
guard let bg1PosY = bg1?.position.y else { return }
if playerPosY - bg0PosY > sceneHeight / 2 + camFollowGap {
print("bg0 is not in the scene")
newPosBgY = bg1PosY + sceneHeight
bg0?.position = CGPoint(x: sceneWidth / 2, y: newPosBgY)
} else if playerPosY - bg1PosY > sceneHeight / 2 + camFollowGap {
print("bg1 is not in the scene")
newPosBgY = bg0PosY + sceneHeight
bg1?.position = CGPoint(x: sceneWidth / 2, y: newPosBgY)
}
}
PS:camFollowGap
是CGFloat
的值,是我将相机放置在播放器上时减去的值。在处理连续背景时,我必须将该值添加到计算中,以避免定位延迟和背景之间出现临时间隙。