how to move Camera smoothly in unity3D?

joi picture joi · Jan 3, 2014 · Viewed 22.9k times · Source

When I want to move Camera from origin position to destination position,it looks so stiff.So if it can set move speed accordding to offset,how to do ?

Answer

Alex Cio picture Alex Cio · Jul 23, 2015

There is a nice tutorial on this problem, it is normally described at the beginning of all tutorials on the unity website. Inside the Survival Shooter Tutorial there is a explanation how to make the movement of the camera to the destination position smooth while moving.

Here is the code for moving the camera. Create a script, add it to the camera and add the GameObject you want to move to, into the scripts placeholder. It will automatically save the Transform component like setup in the script. (In my case its the player of the survival shooter tutorial ):

public class CameraFollow : MonoBehaviour
{
    // The position that that camera will be following.
    public Transform target; 
    // The speed with which the camera will be following.           
    public float smoothing = 5f;        

    // The initial offset from the target.
    Vector3 offset;                     

    void Start ()
    {
        // Calculate the initial offset.
        offset = transform.position - target.position;
    }

    void FixedUpdate ()
    {
        // Create a postion the camera is aiming for based on 
        // the offset from the target.
        Vector3 targetCamPos = target.position + offset;

        // Smoothly interpolate between the camera's current 
        // position and it's target position.
        transform.position = Vector3.Lerp (transform.position, 
                                           targetCamPos,   
                                           smoothing * Time.deltaTime);
    }
}