- Home /
Question by
RLin · Jun 05, 2015 at 03:01 PM ·
instantiateobjectvector3line
Instantiate an object every x meters between two others.
How can I:
Get a straight line between two objects.
Instantiate a new GameObject every x meters on that line, starting with a specified one of the objects.
Comment
Best Answer
Answer by Hellium · Jun 05, 2015 at 03:34 PM
Here is what I would have done :
// Get your "straight line"
Vector3 vector = objectB.transform.position - objectA.transform.position ;
// Instantiate the gameobject every x meters on that line
for( int dist = startingDistanceFromA ; dist < vector.Magnitude ; dist += x )
{
GameObject newGameObject = GameObject.Instantiate( prefab ) ;
newGameObject.transform.position = objectA.transform.position + vector.normalized * dist ;
// Or
// GameObject newGameObject = GameObject.Instantiate( prefab, objectA.transform.position + vector.normalized * dist, Quaternion.identity ) ;
}
Works well, however the usage of Vector3.magnitude is laggy due to the square root function.
Store the value prior to the for loop ?
float maxDist = vector.$$anonymous$$agnitude;
for( int dist = startingDistanceFromA ; dist < maxDist ; dist += x )
Unfortunately, the vector length must be calculated every fixed update for my use, as the value is constantly changing. Optimizing this script is something for another question, though.