Unity - 在对象指向的屏幕边缘获取点?

Unity - Get point on edge of the screen that object directed to?

所以这是我的问题:

我在屏幕中有一个指向特定方向的对象。出于演示目的,我添加了一个 LineRenderer 来显示此方向。

我的最终目标是找到物体与世界点之间的距离,这条紫色光线与屏幕边界(白色轮廓)相交。

float DistToScreenEdge = Vector2.Distance(Object.transform.position, PointOnScreenEdge);

但为此我需要得到这一点,但我不知道该怎么做。

Vector2 PointOnScreenEdge = ???

所以,问题: 如何获得“PointOnScreenEdge”?

请注意,我始终知道物体面向的方向及其世界坐标。

在网上看到说要找到相对于屏幕的世界点,可以使用Camera.ScreenToWorldPoint()Camera.ViewportToWorldPoint(),但是我不知道怎么用他们在这种情况下是正确的。

感谢您的帮助。

GeometryUtility.CalculateFrustumPlanes,其中 returns 构成相机平截头体的六个平面的数组。

Ordering: [0] = Left, [1] = Right, [2] = Down, [3] = Up, [4] = Near, [5] = Far

您对 03 感兴趣,然后可以 Plane.Raycast 对付他们

[SerializeField] private Camera mainCamera;

private readonly Plane[] planes = new Plane [6];

void Update()
{
    // Wherever you get these to from
    Vector3 origin;
    Vector3 direction;

    var ray = new Ray(origin, direction);

    var currentMinDistance = float.Max;
    var hitPoint = Vector3.zero;
    GeometryUtility.CalculateFrustumPlanes(mainCamera, planes);
    for(var i = 0; i < 4; i++)
    {
        // Raycast against the plane
        if(planes[i].Raycast(ray, out var distance))
        {
            // Since a plane is mathematical infinite
            // what you would want is the one that hits with the shortest ray distance
            if(distance < currentMinDistance)
            {
                hitPoint = ray.GetPoint(distance);
                currentMinDistance = distance;
            } 
        }
    }  

    // Now the hitPoint should contain the point where your ray hits the screen frustrum/"border"
    lineRenderer.SetPosition(1, hitPoint);
}

有点取决于你的相机是否真的moving/rotating/scaling你可能只想在开始时一次获得平截头平面。

您还应该在开头缓存 Camera.main 引用 一次