- Home /
Spawning objects based on distance traveled?
I'm trying to spawn tubular objects based on the distance my player object has traveled. Similar to how Flappy Bird places tubes in its game as the player moves in the x direction. I've created prefabs to Instantiate the tubes when needed. I'm calculating the distance my player has traveled with the following code. If I want to spawn such tubes, say for every 5 units my player moves in the x direction, how would I go about this? Could I use distanceTraveled % 5 and then Instantiate the objects based on that? Thanks.
float distanceTraveled = 0;
Vector3 lastPosition;
void Start()
{
lastPosition = transform.position;
}
void Update()
{
distanceTraveled += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;
}
Answer by robertbu · Feb 19, 2014 at 04:38 AM
Making the following assumptions:
That, like the build-in cylinder, you are going to align the top and bottom of the game object with your two positions.
That you've authored the tube to be 1 world unit high.
Then here is code to position, scale, and rotate the object:
GameObject tube = Instantiate(tubePrefab);
Vector3 dir = transform.position - lastPosition;
tube.transform.position = lastPosition + dir/ 2.0f;
tube.transform.localScale = new Vector3(tubeWidth, dir.magnitude, tubeDepth);
tube.transform.rotation = Quaternion.FromToRotation(Vector3.up, dir);
'tubeWidth' and 'tubeHeight' for most uses will be constants.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Programaticly Spawn Powerups? 1 Answer
Multiple Cars not working 1 Answer
Why is the method being called every frame even though it is InvokeRepeating? 1 Answer
Issues with instantiated prefabs 1 Answer