Zoom Method Simplified

So you can simplify the method by removing the zoomAmount variable.
The value of Input.mouseScrollDelta.y can only be three possible values, -1f, 0f, and 1f. All you need to do is check if the scroll wheel has moved if it has, move the target position by the value of Input.mouseScrollDelta.y.

If you wanted to increase the steps between the offsets you could scale Input.mouseScrollDelta.y(see comment).

I also check if the transposer has reached the target. I don’t know how much it affects performance but I don’t like the idea of constantly updating variables that don’t need it.

Note: My offsets are Vecor3’s. I want to play around with moving the z value as well.

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

using Cinemachine;

using UnityEngine;

public class CameraController : MonoBehaviour {
    [SerializeField] CinemachineVirtualCamera _cinemachine;
    CinemachineTransposer _transposer;
    [SerializeField] Vector3 _minFollowOffset;
    [SerializeField] Vector3 _maxFollowOffset;
    /// <summary>
    /// Controls how much the camera will move each frame to catch up to _cameraOffsetTarget
    /// </summary>
    /// <remarks>
    /// Lower values result in slower but smoother movement. 
    /// Larger values result in faster but more jarring movement.
    /// </remarks>
    [SerializeField] float _cameraZoomStep = 10;
    Vector3 _cameraOffsetTarget;


    void Awake() {
        _transposer = _cinemachine.GetCinemachineComponent<CinemachineTransposer>();
        _cameraOffsetTarget = _transposer.m_FollowOffset;
    }

    void Update() {
        ZoomCamera();
    }

    void ZoomCamera() {
        // If scroll wheel moved update _cameraOffsetTarget to its new position
        if(Input.mouseScrollDelta.y != 0) {
            //_cameraOffsetTarget.y += Input.mouseScrollDelta.y * 0.5; // This gives twice as many possible steps between the offsets
            _cameraOffsetTarget.y += Input.mouseScrollDelta.y;
            _cameraOffsetTarget.y = Mathf.Clamp(_cameraOffsetTarget.y, _minFollowOffset.y, _maxFollowOffset.y);
        }
        // If the _transposer offset is not at _cameraOffsetTarget lerp to it
        if(_transposer.m_FollowOffset != _cameraOffsetTarget) {
            _transposer.m_FollowOffset = Vector3.Lerp(_transposer.m_FollowOffset, _cameraOffsetTarget, Time.deltaTime * _cameraZoomStep);
        }
    }
}
2 Likes

We use Lerp, so “_transpose.m_Follow Offset” will never reach “_cameraOffsetTarget”. The values will always differ by a small amount, and in your case, “if” will almost always be true. We solved a similar problem when moving the Unit to the “targetPosition”. For the solution, we introduced an additional field “stoppingDistance”

Using my method the second if statement will only be true on average 105 cycles. It seems like a small price to pay to position an object reliability and consistently.

1 Like

Privacy & Terms