Search code examples
c#unity-game-enginecamera

Follow a GameObject and change camera view at the same time


I am working on a 3D side scroller game in which my camera is following my character using Vector3.lerp.

Currently my camera is looking at the player from a side but at certain points I want the camera to transition to TopView (look at the character from the top) while also keeping a certain height from the character.

I have done this by creating camera settings naming SideView and TopView. Now the problem is that the camera does transitions from SideView to TopView but during transition the camera shakes when it is at the end of the lerp (when the camera is almost at the target position).

How to make this smooth (stop camera shake)?

Note: both camera and character are moving.

Here the source code of my camera follow:

void LateUpdate () 
{
    if(currentCameraSettings != null && target.transform != null)
    {
        targetPos = SetCameraTargetPos(target.transform);

        if(duration != 0)
        {
            transform.position = Vector3.Lerp(transform.position,targetPos,(Time.time - startTime ) / duration );
        }
        else
        {
            transform.position = targetPos;
        }

        SetCameraRotation();
    }
}

SetCameraTargetPos returns the target position after adding height and z-axis distance from the target character.


Solution

  • Sounds like you have the wrong situation for a Lerp. I think what you want to use here is MoveTowards.

    float step = speed * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    

    if its still "jaggedy" for you, try using Time.smoothDeltaTime.