我有一个数组,定义如下的不间断路径;
var path = new [] {
new Vector2(0.4f, 0.2f),
new Vector2(1f, 1.1f),
new Vector2(2f, 1f),
new Vector2(2.5, 0.6f)
}
导致以下可视化;
路径中的点数是可变的。如何确定代表该路径中心的坐标?在这种情况下,中心定义为其中一条线的坐标,在该点处分割路径将导致两条等长的路径。
对点求和并求平均值并不是解决方案,考虑到这将导致坐标不在路径上。
c#或unity3d中是否有可以提供此值的东西,还是我需要学习一些时髦的数学知识?
最佳答案
这是抓住中间点的快速代码示例:
Vector2 GetMidPoint(Vector2[] path)
{
var totalLength = 0d;
for(var i = 0; i < path.Length - 1; i++)
totalLength += GetDistanceBetween(path[i], path[i + 1]);
var halfLength = totalLength / 2;
var currLength = 0d;
for(var i = 0; i < path.Length - 1; i++)
{
var currentNode = path[i];
var nextNode = path[i+1];
var nextStepLength = GetDistanceBetween(currentNode, nextNode);
if (halfLength < currLength + nextStepLength)
{
var distanceLeft = halfLength - currLength;
var ratio = distanceLeft / nextStepLength;
return new Vector2(currentNode.x + (nextNode.x - currentNode.x) * ratio, currentNode.y + (nextNode.y - currentNode.y) * ratio);
}
else
currLength += nextStepLength;
}
throw new Exception("Couldn't get the mid point");
}
public double GetDistanceBetween(Vector2 a, Vector2 b)
{
var x = Math.Abs(a.x - b.x);
var y = Math.Abs(a.y - b.y);
return (Math.Sqrt(Math.Pow(x,2) + Math.Pow(y, 2)));
}