First you will want to define a start and end position in your scene. Create GameObjects
in the editor to place at the start and end positions of your movement path, and drag and drop them into the startObject
and endObject
fields in the script below.
Then you can interpolate between the two positions using the Vector3.Lerp()
function (more details here).
The code below linearly moves your object from startPos
to endPos
over moveDuration
seconds.
public Transform startObject;
public Transform endObject;
[Tooltip("How long the movement will take in seconds.")]
public float moveDuration = 1;
[Tooltip("The delay in seconds before movement starts.")]
public float startDelay = 60;
bool isMoving = false;
bool hasMoved = false;
void Update() {
// if it is time to move, and this object is not moving, and hasn't moved yet
if (Time.timeSinceLevelLoad > startDelay && !isMoving && !hasMoved) {
// start moving (this moves the current object from startObject.position to endObject.position over moveDuration seconds)
StartCoroutine(Move(startObject.position, endObject.position, moveDuration));
}
}
IEnumerator Move(Vector3 startPos, Vector3 endPos, float duration){
// Record that we are about to start moving
isMoving = true;
// timeElapsed will incresase from 0 to duration over the course of the while loop
var timeElapsed = 0f;
while(timeElapsed < duration){
// lerp (linearly interpolate) the position of this object between startPos and endPos
// Use (timeElapsed / duration) to control how close it is to the startPos vs the endPos
transform.position = Vector3.Lerp(startPos, endPos, timeElapsed/duration);
// Wait a frame and record that time has elapsed
yield return new WaitForEndOfFrame();
timeElapsed += Time.deltaTime;
}
// Make sure that the object ends at the correct endPos
transform.position = Vector3.Lerp(startPos, endPos, timeElapsed/duration);
// Record that we are not moving anymore and that this object has moved
isMoving = false;
hasMoved = true;
}