- Home /
Cloning An Object Along A Path Between 2 Points
What i need to make is draw a line not a straight line but a line with spaces, To do this I have 2 points and a prefab(cube) which i want to instantiate many times between those 2 points and the prefab should be instantiated in amounts according to the distance between the 2 points. Thank you.
Answer by hoy_smallfry · Feb 15, 2013 at 01:02 AM
(I'm assuming you know how to instantiate a prefab)
This is a problem easy solved by linear interpolation, or "lerp" as its often times called.
The idea is that you treat the 3D positions as 3D vectors, and therefore you can find the vector between them by subtracting one vector from another:
This vector between the two points has a length, and according to vector multiplication, the vector can be scaled up by a number, which multiplies its length:
If you multiplied it by 3, the resulting vector from the multiplication is 3 times it's size. But, if we multiplied the vector by 1 the result is same vector, and as you can see by the first picture, that would be pointed exactly at the spot A is pointed at. If we multipled it by 0, then the vector would have no length, which is essentially at point B.
SO... depending on what value you multiply by between 0 and 1, you can get a value that runs along the black vector line in the first image. If the value is 0.25, then it is a quarter of the way to A from B, etc.:
Thankfully, Unity provides a function for linear interpolation:
Vector3 point = Vector3.Lerp(startPoint, endPoint, percentage);
So, you can essentially use a for loop from from 0 to 1 that increases by (1.0f/N), where N is the number of dots you want to display in between the two points, and pass the loop value in as the percentage.
Thank you so much, your answer was extremely detailed and helpful.