在两点之间生成x个点数

时间:2018-02-09 12:20:31

标签: c# unity3d

我按以下方式划线:

public class MyLineRenderer : MonoBehaviour {
LineRenderer lineRenderer;

public Vector3 p0, p1;

// Use this for initialization
void Start () {
   lineRenderer = gameObject.GetComponent<LineRenderer>();
   lineRenderer.positionCount = 2;

   lineRenderer.SetPosition(0, p0);
   lineRenderer.SetPosition(1, p1);

    }
}

我怎样才能找到线上10个点从一端到另一端间距相等的点?<​​/ p>

2 个答案:

答案 0 :(得分:3)

您可以使用non-administrative Chocolatey installation生成两点之间的点。将0.5传递给t参数会使其在PositionA和PositionB之间找到中间位置。

要在两点之间生成多个点,您只需在循环中使用Vector3.Lerp

这是一个执行此操作的功能:

void generatePoints(Vector3 from, Vector3 to, Vector3[] result, int chunkAmount)
{
    //divider must be between 0 and 1
    float divider = 1f / chunkAmount;
    float linear = 0f;

    if (chunkAmount == 0)
    {
        Debug.LogError("chunkAmount Distance must be > 0 instead of " + chunkAmount);
        return;
    }

    if (chunkAmount == 1)
    {
        result[0] = Vector3.Lerp(from, to, 0.5f); //Return half/middle point
        return;
    }

    for (int i = 0; i < chunkAmount; i++)
    {
        if (i == 0)
        {
            linear = divider / 2;
        }
        else
        {
            linear += divider; //Add the divider to it to get the next distance
        }
        // Debug.Log("Loop " + i + ", is " + linear);
        result[i] = Vector3.Lerp(from, to, linear);
    }
}

<强> USAGE

//The two positions to generate point between
Vector3 positionA = new Vector3(0, 0, 0);
Vector3 positionB = new Vector3(254, 210, 50);

//The number of points to generate
const int pointsCount = 10;
//Where to store those number of points
private Vector3[] pointsResult;

void Start()
{
    pointsResult = new Vector3[pointsCount];
    generatePoints(positionA, positionB, pointsResult, pointsCount);
}

现在,10个不同的数组点存储在pointsResult变量中。

答案 1 :(得分:0)

如果要在数组中包含线条渲染器的第一个点,可以执行以下操作:

    int amnt = 10; // if you want 10 points
    Vector3[] points = new Vector3[amnt]; // your array of points

    for (int x = 0; x < amnt; x++)
    {
        points[x] = new Vector3((p1.x - p0.x) * x / (amnt-1), 
                                (p1.y - p0.y) * x / (amnt-1), 
                                (p1.z - p0.z) * x / (amnt-1)); // we divide by amnt - 1 here because we start at 0
    }