MouseScrollZoom2D.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using UnityEngine;
  3. namespace Cinemachine.Examples
  4. {
  5. [RequireComponent(typeof(CinemachineVirtualCamera))]
  6. [SaveDuringPlay] // Enable SaveDuringPlay for this class
  7. public class MouseScrollZoom2D : MonoBehaviour
  8. {
  9. [Range(0, 10)]
  10. public float ZoomMultiplier = 1f;
  11. [Range(0, 100)]
  12. public float MinZoom = 1f;
  13. [Range(0, 100)]
  14. public float MaxZoom = 50f;
  15. CinemachineVirtualCamera m_VirtualCamera;
  16. float m_OriginalOrthoSize;
  17. void Awake()
  18. {
  19. m_VirtualCamera = GetComponent<CinemachineVirtualCamera>();
  20. m_OriginalOrthoSize = m_VirtualCamera.m_Lens.OrthographicSize;
  21. #if UNITY_EDITOR
  22. // This code shows how to play nicely with the VirtualCamera's SaveDuringPlay functionality
  23. SaveDuringPlay.SaveDuringPlay.OnHotSave -= RestoreOriginalOrthographicSize;
  24. SaveDuringPlay.SaveDuringPlay.OnHotSave += RestoreOriginalOrthographicSize;
  25. #endif
  26. }
  27. #if UNITY_EDITOR
  28. void OnDestroy()
  29. {
  30. SaveDuringPlay.SaveDuringPlay.OnHotSave -= RestoreOriginalOrthographicSize;
  31. }
  32. void RestoreOriginalOrthographicSize()
  33. {
  34. m_VirtualCamera.m_Lens.OrthographicSize = m_OriginalOrthoSize;
  35. }
  36. #endif
  37. void OnValidate()
  38. {
  39. MaxZoom = Mathf.Max(MinZoom, MaxZoom);
  40. }
  41. void Update()
  42. {
  43. #if ENABLE_LEGACY_INPUT_MANAGER
  44. float zoom = m_VirtualCamera.m_Lens.OrthographicSize + Input.mouseScrollDelta.y * ZoomMultiplier;
  45. m_VirtualCamera.m_Lens.OrthographicSize = Mathf.Clamp(zoom, MinZoom, MaxZoom);
  46. #else
  47. InputSystemHelper.EnableBackendsWarningMessage();
  48. #endif
  49. }
  50. }
  51. }