【问题标题】:How can I set an SKCameraNode's position x and y relative to a node?如何设置 SKCameraNode 相对于节点的位置 x 和 y?
【发布时间】:2017-06-29 12:59:22
【问题描述】:

我正在以编程方式设置我的相机节点。我的目标是让相机跟随玩家节点的 x 轴,但让相机的 y 轴高于“player.position.y”,类似于“player.position.y + 300”。

我在谷歌上搜索了一段时间后发现了这个问题:

cam.position = CGPoint(x: player.position.x, y: player.position.y + 500)

我把它和相机的设置一起放在了 didMove(to:) 中:

cam = SKCameraNode() //initialize and assign an instance of SKCameraNode to the cam variable.
    self.camera = cam //set the scene's camera to reference cam
    //cam.setScale(1.3)

cam.position = CGPoint(x: player.position.x, y: player.position.y + 500)
    addChild(cam) //have cam be a child

我试过把它放在 add child(cam) 行之前和之后,但是 cam.position 行没有效果。

我尝试将我的相机设置为玩家节点和场景的子节点,但无论使用哪种方法,我都可以让相机跟随玩家,但我不知道如何操作 X 和 Y分别地。我能够影响相机位置的唯一方法是使用“设置比例”,但这更多的是全局放大/缩小。

任何建议将不胜感激。

编辑:答案的第一部分就是我所需要的:

cam = SKCameraNode()
player.addChild(cam)
cam.position = CGPoint(x:0,y:500)
self.camera = cam

【问题讨论】:

    标签: ios swift swift3 sprite-kit


    【解决方案1】:

    为什么不直接让camera成为player的child,然后设置relative position为+500,这样你就不用再担心设置camera的x位置了

    cam = SKCameraNode()
    player.addChild(cam)
    cam.position = CGPoint(x:0,y:500)
    self.camera = cam
    

    然后在最终更新时,根据需要设置相机 y:

    let cam = player.childNode[0] as! SKCameraNode //Do whatever you need to do to find the camera
    cam.position.y = 500 - player.position.y //This way if the player goes up 1 point, the camera moves down one point thus keeping it on the same spot
    

    【讨论】:

    • 感谢您的回复!这几乎是完美的!您的代码按预期工作,但有副作用。
    • 有什么副作用?
    • 感谢您的回复!这几乎是完美的!您的代码按预期工作,但有副作用。当我在玩家跳跃时对玩家应用跳跃 (applyImpulse) 时,整个场景似乎会缓慢地跟随玩家向上漂移,直到玩家再次落地。
    • y 根本不应该移动,你是否在你的 didFinishUpdate...didEndUpdate 上应用了它(不记得名字)
    • 哦,我假设玩家在 y 上从 0 开始,如果地面不在 0,那么您也需要考虑这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2018-12-23
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多