codergautamyt

CameraController.cs

Aug 25th, 2021 (edited)
1,205
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. public class CameraController : MonoBehaviour
  5. {
  6.     private Quaternion rotation = Quaternion.identity;  //Creates a quaternion with only zeros (x=0, y=0, z=0, w=0)
  7.     public Transform target; //the player the camera should follow
  8.     public float height; //how heigh the camera should be away from player
  9.     private float speedX; //mouse X
  10.     private float speedY; //mouse Y
  11.     public float horizontalSpeed = 200;//basically some kind of sensitivity (200 worked best for me)
  12.     public float verticalSpeed = 200; //basically some kind of sensitivity (200 worked best for me)
  13.     private float finalDistance;
  14.     public float maxDistance = 5; //maximum distance camera should be away from player
  15.     public float minDistance = 0.5;  //minimum distance camera should be away from player
  16.     private void Start()
  17.     {
  18.     }
  19.     private void Update()
  20.     {
  21.         GetInput(); // update speedX and speedY
  22.         NormalRotation(); //set rotation based off mouse
  23.         CalculateFinalPosition(); //calculate camera position
  24.     }
  25.  
  26.     private void CalculateFinalPosition()
  27.     {
  28.         //Setup temporary variables
  29.         RaycastHit hit;
  30.         Vector3 targetPosition = target.position + target.up * height;
  31.         Vector3 direction = (transform.position - targetPosition).normalized;
  32.         finalDistance = maxDistance;
  33.  
  34.         //Check collision
  35.         if (Physics.Raycast(targetPosition, direction, out hit, Mathf.Infinity)) { finalDistance = hit.distance - 0.1f; }
  36.  
  37.         //Apply position
  38.         finalDistance = Mathf.Clamp(finalDistance, minDistance, maxDistance);
  39.         transform.position = (target.position + target.up * height) - transform.forward * finalDistance;
  40.     }
  41.  
  42.     public void GetInput()
  43.     {
  44.         speedX = Input.GetAxis("Mouse X");
  45.         speedY = Input.GetAxis("Mouse Y");
  46.         print(speedX);
  47.         print(speedY);
  48.     }
  49.  
  50.     private void NormalRotation()
  51.     {
  52.         //Set rotation values
  53.         rotation.x += speedX * horizontalSpeed * Time.deltaTime;
  54.         rotation.y += speedY * verticalSpeed * Time.deltaTime;
  55.         rotation.y = Mathf.Clamp(rotation.y, -50, 90);
  56.  
  57.         //Apply rotation
  58.         transform.rotation = Quaternion.Euler(rotation.y, rotation.x, rotation.z);
  59.     }
  60. }
RAW Paste Data