沿着矢量线以大致定义的距离获得均匀分布的点

时间:2014-09-30 18:35:42

标签: c# distance vectormath

所以我已经推出了一个方法,它在给定的距离返回一组点。

    /// <summary>
    /// Gets all the points between a two vectors at given distance, including the starting and the ending point.
    /// </summary>
    public static List<Vector2> GetPointsAlongTwoVectors(Vector2 startingPoint, Vector2 endingPoint, float distance)
    {
        Vector2 direction = (endingPoint - startingPoint).normalized;
        float totalDistance = (endingPoint - startingPoint).magnitude;
        float increasingDistance = 0.0f;
        List<Vector2> points = new List<Vector2>();

        points.Add(startingPoint);

        if (totalDistance > distance)
        {
            do
            {
                increasingDistance += distance;
                points.Add(startingPoint + increasingDistance * direction);
            } while (increasingDistance + distance < totalDistance);
        }

        points.Add(endingPoint);

        return points;
    }

该方法有效,但我最后想要做的是将这些点均匀地分布在给定的向量上。这使我认为距离最终将转向近似距离,因为它可能无法均匀传播具有完全精确距离的点,但只要方法返回起点,终点和它们之间均匀分布的点,那就没问题。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

也许添加以下代码:

...
float totalDistance = (endingPoint - startingPoint).magnitude;
float sectionsCount = (float)Math.Round(totalDistance / distance, MidpointRounding.AwayFromZero);
distance = totalDistance / sectionsCount;
...

请务必检查sectionsCount为0的情况。