c# - 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;
}
}
解决方案
这是因为Debug.DrawRay
和Physics.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);
}
推荐阅读
- javascript - 用圆括号替换字符串,其中有 % 和数字
- apache - 使用 apache 和 linux ubuntu 在 localhost 上配置 virtualhost 和 .htaccess
- javascript - 如何使 CSS 网格容器始终填充可用的垂直空间
- amazon-web-services - 从网站调用我的 lambda 函数时授权配置异常
- jupyter-notebook - 来自 Navigator 的 Jupyter Notebook 启动错误
- java - 如何修复 NotReadablePropertyException:bean 类的无效属性“freePasses”
- python - 没有外部服务器的 Python GraphQL Ariadne WSGI 示例
- android - 带有 ViewModel 组件的 MVP
- c# - 如何获取 .Net Core 控制台应用程序的 .exe 文件所在目录的路径?
- javascript - 在 js 函数中使用 php(外部 .js 文件)