统一-在屏幕边缘获得指向该对象的点? [英] Unity - Get point on edge of the screen that object directed to?

查看:0
本文介绍了统一-在屏幕边缘获得指向该对象的点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我的问题:

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

我的最终目标是找出对象与此紫色光线与屏幕边框(白色轮廓)相交的世界点之间的距离。

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

但为此我需要了解这一点,而我不知道如何做到这一点。

Vector2 PointOnScreenEdge = ???

因此,问题是: 如何获得该";PointOnScreenEdge";?

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

在Internet上,我读到要查找相对于屏幕的世界点,可以使用Camera.ScreenToWorldPoint()Camera.ViewportToWorldPoint(),但我想不出在这种情况下如何正确使用它们。

感谢您的帮助。

推荐答案

GeometryUtility.CalculateFrustumPlanes,它返回组成相机凹陷的六个平面的数组。

排序:[0]=左,[1]=右,[2]=下,[3]=上,[4]=近,[5]=远

您对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);
}

取决于您的相机是否真的在移动/旋转/缩放您可能希望在开始时仅拍摄一次凹陷平面。

您还应该将Camera.main引用缓存在开头。

这篇关于统一-在屏幕边缘获得指向该对象的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆