如何在 SKCamera 的视图中识别特定节点?

How to identify specific nodes in SKCamera's view?

我正在尝试回收相同的 SKSpriteNode 以制作连续的背景。我将 SKSpriteNode 创建为 bg0bg1bg2,并在呈现场景时正确定位它们。不知何故,下面的代码仅重新定位 bg0 一次。

camSKCameraNode,因此,我正在检查相机是否包含背景节点。由于它们的大小,它们中的任何一个都不应该在相机视口中可见。然而,就像我说的那样,这只有效一次,当相机显示回收时 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
        }
    }
}

好吧,我终于想出了如何实现这一点。我希望这对其他人有帮助。

我最初创建并放置了两个 SKSpriteNode 作为背景作为 bg0bg1,如下所示:

    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 值。在处理连续背景时,我不得不将该值添加到计算中,以避免定位延迟和背景之间出现临时间隙。