gpt4 book ai didi

c# - 获取轨迹渲染器的长度

转载 作者:行者123 更新时间:2023-12-04 01:08:04 24 4
gpt4 key购买 nike

如何获取在 Unity 中绘制的整个 Trail 渲染器的长度?对于线条渲染器,我们可以使用线条的第 1 点和第 2 点来实现这一点,例如:

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

现在这是一个 extension method所以你可以简单地在你的项目中的任何地方使用它,比如

var length = yourTrailRenderer.GetTrailLength();

关于c# - 获取轨迹渲染器的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65681053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com