c# - 获取轨迹渲染器的长度
问题描述
如何获得在 Unity 中绘制的整个 Trail 渲染器的长度?对于线条渲染器,我们可以使用线条的第一个和第二个点来实现这一点,例如:
var length = (position2 - position1).magnitude;
但不幸的是,我找不到相同的轨迹渲染器,因为它使用多个点。那么我该如何实现呢?
解决方案
TrailRenderer.GetPositions
您可以使用例如迭代所有点
public static class TrailRendererExtensions
{
public static float GetTrailLength(this TrailRenderer trailRenderer)
{
// You store the count since the created array might be bigger than the actual pointCount
// Note: apparently the API is wrong?! There it says starting from version 2018.1 the parameter is "out"
// if you get an error for the "out" anyway or if you use older versions instead use
//var points = new Vector3[trailRenderer.positionCount];
//var count = trailRenderer.GetPositions(points);
var count = trailRenderer.GetPositions(out var points);
// If there are not at least 2 points .. well there is nothing to measure
if(count < 2) return 0f;
var length = 0f;
// Store the first position
var start = points[0];
// Iterate through the rest of positions
for(var i = 1; i < count; i++)
{
// get the current position
var end = points[i];
// Add the distance to the last position
// basically the same as writing
//length += (end - start).magnitude;
length += Vector3.Distance(start, end);
// update the start position for the next iteration
start = end;
}
return length;
}
}
这现在是一种扩展方法,因此您可以在项目中的任何地方简单地使用它,例如
var length = yourTrailRenderer.GetTrailLength();
推荐阅读
- azure-container-service - 如何从逻辑应用在 Azure 容器注册表中进行身份验证
- android - Flutter 中的圆形显示动画相当于什么?
- python - 如何扩展numpy数组
- java - 如何在我的 Java Web 应用程序中访问 Heroku ClearDB?
- java - PersonQueue 不是抽象的,不会覆盖 Queue 中的抽象方法 addLast()
- java - 有没有办法简化这个三元语句?
- php - 为什么 money_format() PHP 函数不格式化数字?
- php - php simplexml 加载字符串 xmlParseCharRef:无效的 xmlChar 值 25
- jquery - $.fn.jquery 在将 jquery 更新为新版本时显示旧版本
- mysql - vb.net 中的查询错误返回不正确的双精度值