Advertisement
UnityCoder_Jay

UnityCameraZoom.cs

Jul 25th, 2021 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1. /* Note:
  2. Attach this script to the player or object you want to zoom in on.
  3. You can go into the inspector and change the camera zoom to a different numerical value if you like.
  4. Left click is to zoom in, then left click again to zoom out.
  5. */
  6. using UnityEngine;
  7.  
  8. public class UnityCameraZoom : MonoBehaviour {
  9.    
  10.     // We made a public int that will set the new field of view for the camera.
  11.     public int cameraZoom = 20;
  12.     // We made a public int that is the current field of view for the camera.
  13.     private int cameraNormal = 60;
  14.     // How fast the camera will zoom in and out.
  15.     private float cameraSmooth = 5f;
  16.  
  17.     // A bool to declare if the camera is zoomed.
  18.     private bool cameraZoomed = false;
  19.  
  20.     // Declareing the camera
  21.     private Camera playerCamera;
  22.  
  23.     private void Start() {
  24.         // on start we get the componenet camera.
  25.         playerCamera = GetComponent<Camera>();
  26.     }
  27.  
  28.     private void Update() {
  29.         // If the player presses left mouse button
  30.         if (Input.GetMouseButtonDown(0))
  31.         {
  32.             // then flip the boolean, so if its true set false, if false then set it to true..
  33.             cameraZoomed = !cameraZoomed;
  34.         }
  35.         // if the camera zoom is set to true
  36.         if (cameraZoomed) {
  37.             // set the players camera field of view equal to:
  38.             // the camera fov value, then get the value of the zoom, and find the difference and change it slowly.
  39.             // The speed at which we change it, is called cameraSmooth.
  40.             // We use Time.DeltaTime so the zoom doesn't happen instantly. If you was to remove it, it would do it in 1 frame.
  41.             // instead of multiple frames which would remove the smooth like feature when zooming in..
  42.             playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, cameraZoom, Time.deltaTime * cameraSmooth);
  43.         } else /*else if its not true*/ {
  44.             // players camera fov is equal to:
  45.             // the current fov of the players camera, then we set it back to noraml which is 60, then change the difference slowly
  46.             // with cameraSmooth again.
  47.             playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, cameraNormal, Time.deltaTime * cameraSmooth);
  48.         }        
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement