Hi!
I want to divide lineRenderer to some n parts and get vector3 positions between start position and and position. Right now I’m trying to use Vector3.Lerp for it in a for loop, but cant get the last value of lerp function right. Any help?
var ray2 = Camera.main.ScreenPointToRay (Input.mousePosition);
var layerBuildMask2 = 1 << 21;
var layerCritMask2 = 1 << 22;
var combinedLayer2 = layerBuildMask2 | layerCritMask2;
var lineRenderer : LineRenderer = gameObject.GetComponent("LineRenderer");
var linePos : int = 16;
lineRenderer.SetVertexCount(linePos);
if (Physics.Raycast (ray, hit, Mathf.Infinity, combinedLayer))
{
var distance=Vector3.Distance(selectedBuilding.transform.position,hit.transform.position);
for(s = 0 ; s<linePos ; s++)
{
lineRenderer.SetPosition(s, Vector3.Lerp(hit.transform.position,selectedBuilding.transform.position,distance/s));
}
}
Lerp expects a 0-1 percent as the last input, so just give it 0/15, 1/15, 2/15 … 15/15. I think the confusion is that most people don’t have a 0-1, so have to do math to force it. You’re using lerp for the exact thing it was meant to do:
for(int s=0;s<linePos;s++) {
... lerp(start, stop, s/(linePos-1)) ...
// EX: when s=5, you get 5/15ths, so the point is 1/3rd of the way over
The extra “-1” is because you want to start at 0/15ths and end at 15/15ths (equals 100%.) That’s a total of 16 points.
Divide by zero may be killing the rest of the for loop, and “distance/s” wrong.
Try this:
var targetPos : Vector3 = selectedBuilding.transform.position;
Debug.Log (targetPos);
var clickPos : Vector3 = hit.transform.position;
Debug.Log (clickPos);
lineRenderer.SetPosition(0,clickPos);
for (var s : int = 1; s < linePos; s++)
{
Debug.Log(s);
var percentage : float = s/linePos;
Debug.Log(percentage);
var splitPos : Vector3 = Vector3.Lerp(clickPos,targetPos),percentage);
Debug.Log(splitPos);
lineRenderer.SetPosition(s, splitPos);
}
The last value of Vector3.Lerp() smoothing. The higher its value the faster the object will interpolate to the given position. Use “0” for maximum smoothing and “1” for minimum smoothing.