swift - 如何识别 SKCamera 视图中的特定节点?
问题描述
我正在尝试回收相同的内容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
}
}
}
解决方案
好吧,最后我想出了如何实现这一目标。我希望这对其他人有帮助。
我最初创建并放置了两个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
我将相机放置在播放器上时减去的值。在处理连续背景时,我必须将该值添加到计算中,以避免定位延迟和背景之间出现临时间隙。
推荐阅读
- unreal-engine4 - 与弹丸重叠时的空扫命中结果
- c# - Automapper 和映射复杂集合
- javascript - 类泛型可分配问题
- python - 如何从 excel 中访问值,其中第一列是标题
- python - Pip3 install 不安装 numpy 模块
- javascript - 如何主动检查一个值是否在增加?(javascript)
- ruby-on-rails - 用js响应一个表单提交,得到:ActionController::UnknownFormat
- r - 使用官员包将合并的 docx 文档导入 R
- blockly - 对类类型的块状支持
- android - XML 代码格式在 LinearLayout Android Studio 3.5 中给出错误的子视图排列