Vector3 MousePosInWorldSpace()
{
return Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
ScreenToWorldPoint
returns a point in world space, at the provided z
distance from the camera.
Since Input.mousePosition.z
position is always 0, in the above example, the z
value of the returned point would equal to the z
position of the camera.
In the following example Camera.main.nearClipPlane
distance is provided as the z
distance from camera for the returned world space point. The camera cannot see geometry that is closer to this distance.
Vector3 MousePosInWorldSpace()
{
Vector3 mousePos = Input.mousePosition;
return Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));
}