- Home /
How to update interval between objects in run time?
Hello all,
I have a road with 4 cars, the cars "loop" through the road (one after another). I have a speed, length and time floats to calculate the road length or cars speed when these altered.
My goal is to keep the interval between the cars equal at all time, when distance change. I need the cars to have bigger or smaller interval between them based on road length
My approach is to calculate a variable "float" to be the interval between two adjacent cars, and then based on new distance calculate this variable again and then assign the variable to the interval. This way the cars will adjust them selves based on the road length and I use Mathf.Lerp for smooth adjustment.
Script here:
public IEnumerator SpawnTunnel()
{
for (int i = 0; i < 4; i++)
{
var tunnelScreen = Instantiate(tunnelPrefab, spawnPoint.position, tunnelPrefab.transform.rotation * Quaternion.Euler(0, 0, 0), transform);
tunnels.Add(tunnelScreen);
tunnels[i].GetComponent<Animator>().SetTrigger("FadeIn");
yield return new WaitForSeconds(timeToSpawn);
}
getDistance = true;
}
private void Update()
{
for (int i = 0; i < tunnels.Count; i++)
{
tunnels[i].transform.position += Vector3.forward * speed * Time.deltaTime;
if (getDistance)
{
if (Vector3.Distance(tunnels[i].transform.localPosition, endPoint) < speed)
{
tunnels[i].transform.position = spawnPoint.position;
tunnels[i].GetComponent<Animator>().SetTrigger("FadeIn");
}
}
if (getLenght)
{
deltaTunnel = Mathf.Lerp(tunnels[i].transform.position.x, tunnels[i + 1].transform.position.x, speed * Time.deltaTime);
print("update");
}
getLenght = false;
}
}
public void MoreLenght()
{
currentDis = trackLenght;
currentDis += 80;
trackLenght = currentDis;
endPoint.x = trackLenght;
RecalculateTrackLenght();
}
private void RecalculateTrackLenght()
{
for (int i = 0; i < tunnels.Count; i++)
{
deltaTunnel = tunnels[i].transform.position.x - tunnels[i + 1].transform.position.x;
deltaTunnel = trackLenght / 4;
print("delta is: " + deltaTunnel);
getLenght = true;
}
}
Your answer
Follow this Question
Related Questions
How the heck does Mathf.Lerp work? 2 Answers
Problem with lerping Y axis 0 Answers
How Make a Simple Altimeter? 1 Answer
How would I smooth out a Quaternion? 2 Answers
Vector3.lerp and then wait 1 Answer