如何根据4个世界坐标点计算相机位置?

3

我有4个世界点作为Vector3对象。

我还有一个具有固定旋转的透视摄像机。

我希望保留我的摄像机旋转,并使其以0,0,0为中心,可以保证我的点也是在原点周围生成的。我只需要将相机向后移动,直到它们都在视野中。

我是Unity和3D思维的新手,所以我不太确定我在寻找什么,但我觉得这应该很容易解决?

我认为我可以将相机向后移动,直到获得介于0-1之间的WorldToViewportPoint,但我想应用我已经有的平滑移动函数,该函数需要一个起点和终点,因此我需要在移动相机之前计算一种方法。

任何指针将不胜感激。
谢谢

1个回答

2

通过使用三角函数和一些相机功能来找到相机的水平和垂直视野,您可以找到沿着相机前进方向相机需要移动的距离,以便只查看每个点,然后取最小值。然后,沿着其前进方向将相机移动该距离。

这将处理相机的任何方向/位置!

更多细节请参阅注释:

using System.Linq; // convenience

float GetClosestCameraDist(Vector3 point, float vCot, float hCot)
{ 
    // point to view (camera's local space)
    // v/hCot = cotan of half fovs

    // how far point should be from cam along cam forward to ensure 
    //   point is within fov along camera x/y axes
    float d = Mathf.Max(Mathf.Abs(point.y) * vCot,
                        Mathf.Abs(point.x) * hCot);

    // return how far cam needs to move from its current position 
    //   along cam forward
    // should be negative if it goes cam->  ... origin 
    //           positive if it goes origin ... cam->
    return point.z - d; 
}

Vector3 GetClosestCameraPos(Camera cam, List<Vector3> points)
{
    Transform tCam = cam.transform;

    // cam vertical/horizontal fov in radians
    float vFov = cam.fieldOfView * Mathf.Deg2Rad;
    float hFov = Camera.VerticalToHorizontalFieldOfView(cam.fieldOfView,
            cam.aspect) * Mathf.Deg2Rad;

    float vCot = 1f / Mathf.Tan(0.5f*vFov);
    float hCot = 1f / Mathf.Tan(0.5f*hFov);

    // calculate lowest needed distance from current position to valid position 
    //   along cam forward
    // lowest because the larger this is, the more forward camera is
    float c = points.Select(p => GetClosestCameraDist(tCam.InverseTransformPoint(p),
            vCot, hCot)).Min();

    // go that distance along cam forward from current cam position 
    // to find closest-to-points valid position.
    return c * tCam.forward + tCam.position;
}

此外,如果您希望摄像机稍微向后移动一点,最简单的方法就是调整hFovvFov的值使其更小,这样数学运算就像摄像机的视野更小一样。类似以下内容:
    float vFov = // ...
    float hFov = // ...

    // Will bring the camera back further such that each point is within 
    //   the middle 90% horizontal and 90% vertical rectangle.
    hFov *= 0.9f;
    vFov *= 0.9f;

    // rest of GetClosestCameraPos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接