从触摸位置获取 SCNNode 环境中的向量 swift

Get vector in SCNNode environment from touch location swift

我有我的相机的位置和方向,屏幕上的 CGPoint 触摸位置,我需要在我的 3d SCNNode 环境中我在屏幕上触摸的方向的线(最好是矢量),我怎样才能得到这个?
代码片段会很有帮助。

您可以为此使用 SCNSceneRenderer.unprojectPoint(_:) 方法。

此方法由 SCNView 实现,将您点的坐标作为 SCNVector3。在视图的坐标 space 中设置前两个元素。苹果描述第三个元素的使用:

The z-coordinate of the point parameter describes the depth at which to unproject the point relative to the near and far clipping planes of the renderer’s viewing frustum (defined by its pointOfView node). Unprojecting a point whose z-coordinate is 0.0 returns a point on the near clipping plane; unprojecting a point whose z-coordinate is 1.0 returns a point on the far clipping plane.

您不是在寻找这些点的位置,而是在寻找连接它们的线。只需减去两者即可得到该行。

func getDirection(for point: CGPoint, in view: SCNView) -> SCNVector3 {
    let farPoint  = view.unprojectPoint(SCNVector3Make(point.x, point.y, 1))
    let nearPoint = view.unprojectPoint(SCNVector3Make(point.x, point.y, 0))

    return SCNVector3Make(farPoint.x - nearPoint.x, farPoint.y - nearPoint.y, farPoint.z - nearPoint.z) 
}