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;
}

1 Answer

1

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.