If your object don’t need to check for collisions while moving, the best way is using Lerp (or Slerp, for rotations) in a coroutine. Suppose you want the object to go from pointA to pointB in time seconds:
public var moving: boolean = false;
function MoveFromTo(pointA: Vector3, pointB: Vector3, time: float){
if (moving) return; // ignore other calls while moving
moving = true; // signals "I'm moving, don't bother me!"
var t: float = 0;
while (t < 1){
t += Time.deltaTime / time; // sweeps from 0 to 1 in time seconds
transform.position = Vector3.Lerp(pointA, pointB, t); // set position proportional to t
yield; // leave the routine and return here in the next frame
}
moving = false; // finished moving
}
This is a coroutine, so you can “fire and forget”: just call the routine and go ahead - it will run without any intervention. If you need to know when it has finished, check the moving variable - it will be true while moving.
The same idea applies to rotations or vectors: just replace the line using Lerp to the equivalent using Slerp. If you like quaternions, use Quaternion.Slerp like below:
...
transform.rotation = Quaternion.Slerp(rotationA, rotationB, t);
...
where rotationA and rotationB are quaternions. But if you afraid these strange creatures and prefer vectors, you can do something like this:
...
transform.forward = Vector3.Slerp(oldDirection, newDirection, t);
...
what would make the object gradually turn its front to newDirection vector.
Better yet, you can move and rotate at the same time using the same function! Just use the two lines in the same loop:
...
transform.position = Vector3.Lerp(...);
transform.rotation = Quaternion.Slerp(...);
...
EDITED: Using coroutines in C# is somewhat tricky. To easy things, I’m posting a C# version below. I’m not a C# expert, so this script may have some stupid things (if any, let me know, C# experts) but it works!
public bool moving = false;
IEnumerator MoveFromTo(Vector3 pointA, Vector3 pointB, float time){
if (!moving){ // do nothing if already moving
moving = true; // signals "I'm moving, don't bother me!"
float t = 0f;
while (t < 1f){
t += Time.deltaTime / time; // sweeps from 0 to 1 in time seconds
transform.position = Vector3.Lerp(pointA, pointB, t); // set position proportional to t
yield return 0; // leave the routine and return here in the next frame
}
moving = false; // finished moving
}
}
You can’t call coroutines directly in C# - you must use StartCoroutine:
StartCoroutine(MoveFromTo(pA, pB, time));