Get vector in SCNNode environment from touch location swift

倖福魔咒の 提交于 2019-12-12 04:14:17

问题


I have the position and orientation of my camera, the CGPoint touch location on the screen, I need the line (preferably vector) in the direction that I touched on the screen in my 3d SCNNode environment, how can I get this?
A code snippet would be very helpful.


回答1:


You can use the SCNSceneRenderer.unprojectPoint(_:) method for this.

This method, which is implemented by SCNView, takes the coordinates of your point as a SCNVector3. Set the first two elements in the coordinate space of your view. Apple describes the use of the third element:

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.

You are not looking for the location of these points, but for the line that connects them. Just subtract both to get the line.

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) 
}


来源:https://stackoverflow.com/questions/44991038/get-vector-in-scnnode-environment-from-touch-location-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!