【问题标题】:Generate x amount of points between two points在两点之间生成 x 个点
【发布时间】:2018-02-09 22:21:49
【问题描述】:

我按以下方式做了一行:

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 个点?

【问题讨论】:

  • 你有位置 A 和 B 并且在这两个位置之间找到 10 个等距位置?
  • @Programmer 是的

标签: c# unity3d


【解决方案1】:

您可以使用Vector3.Lerp 在两点之间生成一个点。将0.5 传递给它的t 参数将使它在PositionA 和PositionB 之间的middle 位置。

要在两点之间生成多个点,您只需在循环中使用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);
    }
}

用法

//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 变量中。

【讨论】:

    【解决方案2】:

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

        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
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 2014-03-30
      • 2022-08-07
      • 2012-11-16
      • 1970-01-01
      相关资源
      最近更新 更多