Add smoothing to camera mover

Viewed 44

Hi I have a script that adjusts the distance of an camera in unity to make sure an object is always fully in the view of the camera. I do this like so:

Vector3 characterSize = UpdateBounds(totalPoints).size;
float objectSize = Mathf.Max(Mathf.Max(characterSize.x / 2, characterSize.y / 2), characterSize.z / 2);
float cameraView = 2f * Mathf.Tan(0.5f * Mathf.Deg2Rad * Camera.main.fieldOfView);   
float rigRadius = cameraPadding * objectSize / cameraView;

In this case the rigRadius is the distance from the subject to make sure the camera view contains the total object.

The problem i am having is that when the object has a big change in size over a relativly small time period. The camera movement feels jerky and not smooth at all.

So how do i adjust this code to add some sort of a smoothing value? I just can't seem to figure it out.

As far as i managed to figure out I need to smooth the rigRadius value but i dont know how :(

1 Answers

Have a target radius that your current radius smoothly moves towards.

For best(-ish) results, use a formula where the "speed" of the smoothing is dependent on how far the current situation is from target situation (Note: In this case, situation = radius). In other words, zoom speed depends on the current zoom state rather than a fixed starting point.

So really far (for example after a big, fast change) = really fast (the start of the smoothing is quick), but really close = really slow (so the end of the smoothing is slow).

Here's a decent tutorial on this for 2D: https://youtu.be/AvnrywsoTe0

Note how the lerp uses current camera ortho size rather than a fixed "starting" ortho size to apply the zoom, effectively making the effect I described, where zooming speed depends on current zoom and its "distance" to target zoom.

Related