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