So I put Cinemachine in long time ago for a follow camera, but what was still nagging at me was there was no way to change the zoom during play… I got into the next section and just couldn’t take it anymore so here’s a script what will let you zoom in and out with the mouse wheel… if we don’t eventually cover a rotate camera, I will make one to post against this lecture in the future…
the script needs to be called ScrollZoom.cs
place this script on the vcam pointed at your player
make sure your vcam is using “Framing Transposer” in the body section.
EDIT- the script now includes reducing your lookahead time when you scroll in close to your player. If the lookahead time is set to zero, no change will happen. If you have a lookahead time you like when you are fully zoomed out, the script will now reduce that lookahead time when you zoom in to keep your player in frame better.
NOTE - once you have a lookahead time you like, uncheck “Save During Play” or it will continuously override your favorite lookahead time whenever you exit play mode. This is not necessary if your lookahead time is 0, as no change will take place anyway.
(You can always revert it from your prefab if you forget this step)
using UnityEngine;
using Cinemachine;
public class ScrollZoom : MonoBehaviour
{
CinemachineVirtualCamera vcam;
CinemachineFramingTransposer framingTransposer;
[SerializeField] float startingCameraDistance = 10;
[Space(5)]
[SerializeField] float minCameraDistance = 5;
[SerializeField] float maxCameraDistance = 40;
[Space(10)]
[Range(0.025f, 1f)]
[SerializeField] float scrollSensitivity = 0.5f;
public bool negateScrollDirection = false;
float maxLookaheadTime;
float lookaheadAdjusted;
void Start()
{
vcam = GetComponent<CinemachineVirtualCamera>();
framingTransposer = vcam.GetCinemachineComponent<CinemachineFramingTransposer>();
framingTransposer.m_CameraDistance = startingCameraDistance;
maxLookaheadTime = framingTransposer.m_LookaheadTime;
}
// Update is called once per frame
void Update()
{
if (Input.mouseScrollDelta.y != 0)
{
var scroll = Input.mouseScrollDelta.y;
var adjustedScroll = scroll * scrollSensitivity;
NewCameraDistance(adjustedScroll);
}
}
private void NewCameraDistance(float adjustedScroll)
{
if (negateScrollDirection)
{
framingTransposer.m_CameraDistance =
Mathf.Clamp(framingTransposer.m_CameraDistance += adjustedScroll, minCameraDistance, maxCameraDistance);
}
else
{
framingTransposer.m_CameraDistance =
Mathf.Clamp(framingTransposer.m_CameraDistance -= adjustedScroll, minCameraDistance, maxCameraDistance);
}
if (maxLookaheadTime == 0) return;
lookaheadAdjusted = Mathf.Clamp(framingTransposer.m_CameraDistance / maxCameraDistance, 0.1f, maxLookaheadTime);
framingTransposer.m_LookaheadTime = lookaheadAdjusted;
}
}