In my game, you can create a custom route. You do this by clicking on the different places. The vehicle has to move from the first element (Where the clicked gameobject is stored) to the last element. The length of the array (“route”) can differ.
So, how do I let my vehicle move to the gameobject in element 0 till the last element?
Currently, I have something like this, but it doesn’t work.
var index = 1;
function Update() {
if(index < route.length)
{
transform.position = Mathf.Lerp(route[index-1],route[index],Time.time);
if(transform.position == route[index]) index++;
}
}
Your Lerp() will only work once (at the start of the game) using Time.time, and a Lerp() must be executed repeatedly over many frames, so increasing your index every frame will fail. There are many ways to code this functionality. Figure out the best way will depend on the larger context of your app. Here is a bit of code that does what you specify. Note the ‘yield’ in he code. This uses Start() as a co-routine. This script expects the positions in ‘route’ to be set in the Inspector.
#pragma strict
public var route : Vector3[];
public var speed = 1.5;
function Start() {
for (var v : Vector3 in route) {
while (transform.position != v) {
transform.position = Vector3.MoveTowards(transform.position, v, Time.deltaTime * speed);
yield;
}
}
}