简体   繁体   中英

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

I have an array that defines an unbroken path as follows;

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

Which results in the following visualisation;

路径点图

The number of points in the path is variable. How can I determine the co-ordinate that represents the centre of this path? Centre in this case is defined as a co-ordinate on one of the lines where splitting the path at that point would result in two paths of equal length.

Summing the points and averaging is not a solution, considering this would result in a co-ordinate not on the path.

Is there something in or that can provide this value, or do I need to whip out some funky math stuff?

For each segment, calculate (and store) the segment's length. Add up all lengths and divide total by 2.

Iterate over all the segments in path order, subtracting the length of each segment from this halved total until the current segment length is greater than the remaining total.

Then compute the point at that length along that line segment.

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

Here's a quick code example to grab the mid 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)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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