繁体   English   中英

如何找到连接的线阵列的中心坐标?

[英]How can I find the centre co-ordinates of an array of connected lines?

我有一个数组,定义如下的不间断路径;

var path = new [] { 
    new Vector2(0.4f, 0.2f), 
    new Vector2(1f, 1.1f), 
    new Vector2(2f, 1f), 
    new Vector2(2.5, 0.6f)
}

导致以下可视化;

路径点图

路径中的点数是可变的。 如何确定代表该路径中心的坐标? 在这种情况下,中心定义为两条线之一上的坐标,其中在该点处分割路径将导致两条长度相等的路径。

求和并求平均值并不是解决方案,考虑到这将导致坐标不在路径上。

中是否有可以提供此值的东西,还是我需要学习一些时髦的数学知识?

对于每个段,计算(并存储)段的长度。 将所有长度相加,然后将总数除以2。

按路径顺序遍历所有段,从此减半的总和中减去每个段的长度,直到当前段的长度大于其余的总和。

然后沿着该线段计算该长度处的点。

https://math.stackexchange.com/questions/409689/how-do-i-find-a-point-a-given-distance-from-another-point-along-a-line

https://math.stackexchange.com/questions/175896/finding-a-point-along-a-line-a-certain-distance-away-from-another-point

这是一个抓住中间点的快速代码示例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM