首页 > 解决方案 > Unity Raycast() 和 DrawRay() 使用相同的输入创建不同的光线

问题描述

我正在尝试创建弯曲的射线,并且需要列出弯曲的射线击中的对象。我可以使用 Debug.DrawRay() 绘制弯曲的射线。但是,当我为 Raycast() 提供与 DrawRay() 相同的参数时,它会创建非常不同的 Ray(我猜是因为我看不到 Ray)。Raycast() 的射线击中了我在图像中突出显示的对象。但是 DrawRay() 的 Ray 距离太远,无法击中突出显示的对象。我怎样才能让他们创建相同的光线? 在这里你可以看到不同之处

//Here is the code:

public void CurveCast(Vector3 origin, Vector3 direction, Vector3 gravityDirection, int smoothness, float maxDistance, float direction_multiply, float radius)
{
    Vector3 currPos = origin, hypoPos = origin, hypoVel = (direction.normalized / smoothness) * direction_multiply;
    List<Vector3> v = new List<Vector3>();        
    float curveCastLength = 0;

    Ray ray;
    RaycastHit hit;
    hit_list = new List<RaycastHit>();
    while (curveCastLength < maxDistance)
    {
        ray = new Ray(currPos, hypoVel);

        Debug.DrawRay(currPos, hypoVel, Color.white);
        if (Physics.Raycast(currPos, hypoVel, out hit)) // if (Physics.SphereCast(ray, radius, out hit,maxDistance))
        {
            hit_list.Add(hit);
        }


        v.Add(hypoPos);
        currPos = hypoPos;
        hypoPos = currPos + hypoVel + (gravityDirection * Time.fixedDeltaTime / (smoothness * smoothness));
        hypoVel = hypoPos - currPos;
        curveCastLength += hypoVel.magnitude;
    }
} 

标签: c#unity3draycasting

解决方案


这是因为Debug.DrawRayPhysics.Raycast不完全相同。

Debug.DrawRay中,射线的长度由矢量幅度定义。您可以在文档中看到它

在世界坐标中从 start 到 start + dir 绘制一条线。

对于Physics.Raycast,射线的长度与方向无关,可以设置为参数。它的默认值是无限的,所以如果你不定义它,即使方向向量很短,光线投射也会去无穷大。请参阅文档

从点原点沿方向方向投射一条长度为 maxDistance 的射线,针对场景中的所有碰撞器。

因此,您的解决方案是为 Raycast 函数提供适当的距离:

Debug.DrawRay(currPos, hypoVel, Color.white);
if (Physics.Raycast(currPos, hypoVel, out hit, hypoVel.magnitude())) // if (Physics.SphereCast(ray, radius, out hit,maxDistance))
{
    hit_list.Add(hit);
}

推荐阅读