With lookat() I can get my object to face in a right direction. But how can I animate from the initial rotation to the lookat rotation. Like, I want the initial rotation be the first key-frame and the second key-frame is my lookat rotation. And I want to interpolat between them smoothly.
You can probably interpolate with Quaternion.Slerp().
Just off the top of my head:
Quaternion startRotation, endRotation;
float period, time;
Vector3 point;
void LookAt(Vector3 point) {
startRotation = transform.rotation;
endRotation = Quaternion.LookFromTo(transform.forward, point - transform.position);
float time = 0f;
float period = 3f; // it will take 3 sec to look
this.point = point;
enabled = true;
}
void Update() {
time += Time.deltaTime;
if(time >= period) {
transform.LookAt(point);
enabled = false;
}
else {
transform.rotation = Quaternion.Slerp(startRotation, endRotation, time/period);
}
}
This solution will take a constant time to look at any point regardless of how many degrees you need to turn. You could change the look period by calculating the angle with Vector3.Angle(transform.forward, point - transform.position) and dividing by a rotational speed.
Instead of the lookat function, create a target rotation quaternion with LookRotation. Then save the initial rotation (initialRot = transform.rotation) and interpolate using transform.rotation = Slerp(initialRot, targetRot, ratio). Where ratio is a floating point value representing the interpolation between zero and one. You’ll probably want to animate the value with something similar to ratio += Time.deltaTime * animationSpeed. You might want to replace ratio in the Slerp call with Mathf.Clamp(ratio, 0.0f, 1.0f).