- Home /
Camera field of view and Mathf.Lerp, camera FOV not moving to value specified
Hello!
I'm using mathf.Lerp to change the camera FOV smoothly when the player hits a trigger. The script I have written for this does work, however the FOV is not changing to the value specified in the script and never goes below 30f.
I have the default FOV set to 40 and the target FOV set to 15. When the script is triggered the FOV changes from 40 to 30. I tried lowering the target FOV to 5 and but the lowest it will go when the script is ran is 27.
Am I using mathf.lerp incorrectly or should I be using something else?
Here's a snippet from my script:
private float targetFOV = 15.0f;
private float defaultFOV = 40.0f;
public float speed = 0.2f;
if (legsTrigger.isTriggerOn == true)
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, targetFOV, speed * Time.deltaTime);
}
else if (!legsTrigger.isTriggerOn)
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, defaultFOV, speed * Time.deltaTime);
}
Answer by Firas4d · Apr 22, 2018 at 08:00 AM
Hi, It seems like that the time while isTriggerOn is true isn't enough for the lerp function to reach the second parameter value, try to increase the speed to make sure this is really the case. Another note, the output of your lerps will never reach the target as long as the speed x Time.deltaTime is less than one, it will surly get closer and closer to the target each frame but it won't be exactly at the targetFOV which is 15, for instance. And if the speed x Time.deltaTime >= 1 then there will be no in-between values. Personally I'd like to keep the lerp linear to prevent any unexpected behaviors as follow :
t += Time.deltaTime * speed;
t = Mathf.Clamp(t, 0.0f, 1.0f);
Camera.main.fieldOfView = Mathf.Lerp(defaultFOV, targetFOV, t);
so at t = 0 the output is exactly equal to defaultFOV and at t = 1 the output is exactly equal to targetFOV.
Thanks for the reply, I'll give that go.
$$anonymous$$uch appreciated!
O$$anonymous$$, I'm a bit dense here and still learning this stuff (it's my first project).
I tried as you suggested, it works the first time the player enters the trigger, but when the player leaves the trigger or re-enters after that the camera jumps between the two values instantly with no smooth movement.
what did I do wrong?
So I can see what's going wrong (I think). I printed out "t" to the console. When the player enters the trigger I see "t" go from 0 to 1 and the field of view zooms in. "t" then stays at 1 whether a trigger is entered or not so I guess that's the issue? How do I fix it?
cheers