使用 Raycast 和 Triangular 函数测量长度,Unity3D

Measure the length using the Raycast and Triangular functions, Unity3D

我正在使用 Unity 在移动环境中开发 AR。

* 顶部和底部已更改 :)

当前程序如下:

1.测量移动设备的坡度。

float angle = Camera.main.transform.eulerAngles.x * Mathf.Deg2Rad;

2。在移动屏幕上的两个点向表面发射射线(顶部、底部)

3。测量移动设备与其表面之间的高度差(Y 轴)

Vector3 CameraPoint = Camera.main.transform.position;
Vector3 SurfacePoint = new Vector3(CameraPoint.x, Bottom.y, CameraPoint.z);
float H = CameraPoint.y - SurfacePoint.y; 

4.测量水平线的长度以利用比例表达式。

float W = Vector3.Distance(Top, SurfacePoint); 
float w = Vector3.Distance(Top, Bottom);   

5.使用比例表达式,计算小三角形的高度。

H:W = h:w => H * w = W * h => ∴ h = (H * w) / W

float h = ((H * w) / W);

6.有两条线(h,w)和相机的斜率,我想测量紫色线的长度。

这两个表达式如下。

x = 1/(1/w + tan(90-θ)/h)

y = tan(90-θ)/(1/w + tan(90-θ)/h)

7.为防止无穷大,tanθ改为cosθ,sinθ.

* tanθ = sinθ / cosθ
* tan(90 - θ) = cosθ / sinθ

x = 1/(1/w + cosθ/(h * sinθ))

y = (cosθ/sinθ)/(1/w + cosθ/(h * sinθ))

8.由于表达式太复杂,我做了一个简单的更改。

var x = (h * w * Mathf.Sin(angle)) / (h * Mathf.Sin(angle) + w * Mathf.Cos(angle));

var y = (h * w * Mathf.Cos(angle)) / (h * Mathf.Sin(angle) + w * Mathf.Cos(angle));

9.我测量了距离(0,0), (x, y)

float Object_height = Vector2.Distance(Vector2.zero, new Vector2(x, y));

目前所需长度是通过上述计算方法测得的。 但它不能正常工作。

我要的是紫色的长度

我只知道星形坐标,相机的斜率,紫色线的斜率

紫色线的斜率与相机的斜率相同。

下图为失败案例

我觉得红光和黄光差距越大,数值越不一样。

哪一部分是错误的?

告诉我如何使用三角函数得到紫色线的长度。

借助 Unity 的 Ray class/struct,无需任何三角函数即可轻松实现这一点,它提供了方便的 GetPoint(float distance) 方法。 获取从相机到近处光线投射的距离是微不足道的(.magnitude),而不是进行第二次光线投射,这足以创建一条光线,并在给定距离处查询一个点。从您的示例中获取紫色线的长度只是做另一个 .magnitude

的问题
    startPos=transform.position;    // to be replaced with camera position
    var hitpoint1=targetA.position; // to be replaced with raycasts hit1
    var hitpoint2=targetB.position; // to be replaced with reaycast hit2
    Ray rayB=new Ray(startPos,hitpoint2-startPos);
    float dist=(hitpoint1-startPos).magnitude;
    var purpleEndPoint=rayB.GetPoint(dist);

    Debug.Log("purple line length ="+(hitpoint1-purpleEndPoint).magnitude);