- Home /
Camera field of view whilst sprinting.
Hi, I am currently working on a sprint script for my FPS character. Currently, it looks like this.
function Update () {
var motorScript = transform.GetComponent(CharacterMotor);
if (Input.GetButtonDown("Sprint"))
{
motorScript.movement.maxForwardSpeed = 10;
Camera.main.fieldOfView = 43;
}
if (Input.GetButtonUp("Sprint"))
{
motorScript.movement.maxForwardSpeed = 4;
Camera.main.fieldOfView = 48;
}
}
I want the camera's field of view to change smoothly to represent the sprint, as you may have seen in other games, such as Skyrim. At the moment, however, the drastic value change makes the cut choppy and unrealistic. How can I make the transition smooth, as though I were moving the Field of View slider rather than changing values?
Answer by save · Mar 05, 2012 at 03:34 PM
You'd use some sort of smoothing algorithm to it. Luckily Unity has prepared for this - for instance Mathf.SmoothStep() or Mathf.Lerp(). Perhaps something like:
private var fov : float = 43.0; private var fovTargetSprint : float = 48.0; private var fovTargetNormal : float = 43.0;
function Update () { if (Input.GetButton("Sprint")) { if (fov<fovTargetSprint) fov = Mathf.Lerp(fov, fovTargetSprint, 10*Time.deltaTime); } else { if (fov>fovTargetNormal) fov = Mathf.Lerp(fov, fovTargetNormal, 10*Time.deltaTime); } }
I'd also check if the character position is greater than a couple of small square lengths to turn the fov back to normal, so it wouldn't look weird when holding down Sprint while facing a wall. To get started check out Vector3.sqrMagnitude.
Use GetButton ins$$anonymous$$d (script will update as soon as Quato have had her coffee).
Answer by synapse · Mar 06, 2012 at 02:27 PM
Thanks, here is the completed script if anyone wants to use it.
function Update () {
Screen.showCursor = false;
var motorScript = transform.GetComponent(CharacterMotor);
if (Input.GetButton("Sprint")){
motorScript.movement.maxForwardSpeed = 10;
if (Camera.main.fieldOfView>43){
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, 43, 10*Time.deltaTime);
}} else {
motorScript.movement.maxForwardSpeed = 6;
if (Camera.main.fieldOfView<48){
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, 48, 10*Time.deltaTime);
}
}
}