c# - Unity Raycast() 和 DrawRay() 使用相同的输入创建不同的光线

标签 c# unity-game-engine raycasting

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

//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;
    }
} 

最佳答案

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

Debug.DrawRay中,光线的长度由矢量幅度定义。您可以see it in the doc :

Draws a line from start to start + dir in world coordinates.

对于Physics.Raycast,光线的长度与方向无关,可以设置为参数。它的默认值是无穷大,因此如果不定义它,即使方向矢量很短,光线转换也会趋于无穷大。 See the doc :

Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the scene.

因此,您的解决方案是为 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);
}

关于c# - Unity Raycast() 和 DrawRay() 使用相同的输入创建不同的光线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172986/

相关文章:

c# - 获取执行我的托管程序集/主机 CLR 运行时的进程 ID/名称(CLR 运行时主机位置)

c# - 如何在 Unity 中每次更新时插入一个获得新位置的相机?

javascript - 如何使用 three.js 'wrap' 球体上的平面?

c# - Raycast 没有击中我点击的内容

c# - HTTPS 流量的代理服务器证书

c# - linq to sql 从性能索引列开始

c# - 双淘汰括号算法

c# - 在 C# 中创建已知长度的数组

ios - Applovin - 架构 armv7 的 undefined symbol

c++ - 设置射线(原点,方向)和三角形交点(无glm)