首页 > 解决方案 > 如何识别 SKCamera 视图中的特定节点?

问题描述

我正在尝试回收相同的内容SKSpriteNode以制作连续的背景。我创建SKSpriteNodebg0, bg1,bg2并在呈现场景时正确定位它们。不知何故,下面的代码只重新定位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
        }
    }
}

标签: swiftsprite-kitskcameranode

解决方案


好吧,最后我想出了如何实现这一目标。我希望这对其他人有帮助。

我最初创建并放置了两个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:camFollowGapCGFloat我将相机放置在播放器上时减去的值。在处理连续背景时,我必须将该值添加到计算中,以避免定位延迟和背景之间出现临时间隙。


推荐阅读