A Camera zoom-in coroutine but based on progress

I would like to know what approaches to take in order to create a coroutine similar to a scoping in effect of a sniper.

Goals:

  • There is a value of scope speed

  • Get the value of how close toward the target FOV is from current FOV.

  • Get the duration needed in order to reach the target FOV with the scope speed

Mechanics:

  • The player can toggle between zoom in and zoom out at any time during zooming process
  • Zooming out goes back to default FOV and zoom in goes to a set value like 30.

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

Also…

Camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.

There’s even a dedicated forum: Unity Engine - Unity Discussions

If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.

private Vector3 WhereMyCameraIsLocated;
private Vector3 WhatMyCameraIsLookingAt;

void LateUpdate()
{
  cam.transform.position = WhereMyCameraIsLocated;
  cam.transform.LookAt( WhatMyCameraIsLookingAt);
}

Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.