Weapon Zoom Field Of View - Interpolate rather then switch

I made the FOV Lerp to have a nicer transition.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponZoom : MonoBehaviour
{
    [SerializeField] private Camera playerCamera;
    [SerializeField] private float zoomedOutFOV = 60f;
    [SerializeField] private float zoomedInFOV = 30f;
    [SerializeField] private float zoomSpeed = 5f;    

    private void Awake() {
        playerCamera.fieldOfView = zoomedOutFOV;
    }

    private void Update() {
        CheckZoom();
    }

    private void CheckZoom() {
        if (Input.GetMouseButton(1) && playerCamera.fieldOfView > zoomedInFOV){
            Zoom(zoomedInFOV);
        } else if (!Input.GetMouseButton(1) && playerCamera.fieldOfView < zoomedOutFOV) {
            Zoom(zoomedOutFOV);
        }
    }

    private void Zoom(float targetFOV) {
        playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, targetFOV, Time.deltaTime * zoomSpeed);
    }
}

would need a bit of refactoring though

4 Likes

Agreed. I have tried both and this seems to work nicely. Great job using Mathf.Lerp().

1 Like

Beautiful!!! I’ve tried so many times to work this out by myself, but boy how I struggle with Lerp… It worked fine with your solution.

1 Like

Privacy & Terms