Reputation: 249
I have made a line in the following way:
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);
}
}
How can I find, for example, 10 points on the line that are equally spaced from end to the other?
Upvotes: 1
Views: 2040
Reputation: 4333
If you want to include the first point of the line renderer in the array, you can do the following:
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
}
Upvotes: 0
Reputation: 125245
You can use Vector3.Lerp
to generate a point between two points. Passing 0.5
to its t
parameter will make it give you the middle position between PositionA and PositionB.
To generate multiple points between two points, you just have to use Vector3.Lerp
in loop.
Here is a function to do this:
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);
}
The 10 different array points are now stored in the pointsResult
variable.
Upvotes: 3