Created
October 3, 2022 13:25
-
-
Save nicetrysean/3553bf5b9c594c18cd7542cbee05c002 to your computer and use it in GitHub Desktop.
Zoom via scroll wheel using DoTween
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using DG.Tweening; | |
using DG.Tweening.Core; | |
using DG.Tweening.Plugins.Options; | |
using UnityEngine; | |
public class CameraZoom : MonoBehaviour | |
{ | |
[SerializeField] private new Camera camera; | |
[SerializeField] private Ease easeType = Ease.InOutExpo; | |
[SerializeField] private float animationDuration = 1f; | |
[SerializeField] private float maxZoom = 120f; | |
[SerializeField] private float minZoom = 25f; | |
private float _targetFov; | |
private TweenerCore<float, float, FloatOptions> _tween; | |
private void OnValidate() | |
{ | |
// If we don't have a camera, skip this! | |
if (Camera.main == null) | |
{ | |
Debug.LogError("No main camera found"); | |
return; | |
} | |
// Find camera automatically and cache it | |
camera = Camera.main; | |
} | |
private void Start() | |
{ | |
// Set our target as what our camera is currently set to | |
_targetFov = camera.fieldOfView; | |
} | |
private void Update() | |
{ | |
// if we don't have a camera, don't do anything | |
if (!camera) return; | |
TweenCameraByMouseScrollPosition(); | |
} | |
private void TweenCameraByMouseScrollPosition() | |
{ | |
var mouseInput = UnityEngine.Input.GetAxis("Mouse ScrollWheel"); | |
if (mouseInput != 0) | |
{ | |
// Clamp target zoom | |
_targetFov = Mathf.Clamp(mouseInput + _targetFov, minZoom, maxZoom); | |
// Clean up old tween if it exists | |
if (_tween != null && _tween.IsActive()) | |
{ | |
_tween.Kill(); | |
} | |
_tween = camera.DOFieldOfView(_targetFov, animationDuration).SetEase(easeType); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment