簡體   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