dronkowitz

CameraController.cs

Mar 24th, 2021 (edited)
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.SocialPlatforms;
  5.  
  6. public class CameraController : MonoBehaviour
  7. {
  8.     public Transform sonic;
  9.     public Transform cam;
  10.    
  11.  
  12.     public Vector3 offset;
  13.  
  14.     public LayerMask cameraMask;
  15.     // Start is called before the first frame update
  16.     void Start()
  17.     {
  18.  
  19.     }
  20.  
  21.     // Update is called once per frame
  22.     void Update()
  23.     {
  24.         Vector2 look = new Vector2();
  25.  
  26.         look.x = Input.GetAxis("Mouse X");
  27.         look.y = Input.GetAxis("Mouse Y");
  28.  
  29.         transform.position = sonic.position - (transform.forward * 0.5f + sonic.up * 2);
  30.        
  31.  
  32.         float cameraDistance = 8;
  33.         if (Physics.Raycast(transform.position, -transform.forward, out RaycastHit hit, 8.3f, cameraMask))
  34.         {
  35.             float distance = Vector3.Distance(transform.position, hit.point);
  36.             cameraDistance = distance - 0.3f;
  37.         }
  38.         float ratio = cameraDistance / 8;
  39.         cam.localPosition = new Vector3(0, 5 * ratio, -cameraDistance);
  40.  
  41.  
  42.  
  43.         Look(look);
  44.     }
  45.  
  46.     private float xRotation;
  47.  
  48.     public void Look(Vector2 lookDirection)
  49.     {
  50.  
  51.         transform.Rotate(Vector2.up, lookDirection.x*5);
  52.        
  53.  
  54.  
  55.         xRotation -= lookDirection.y; //Subtract mouse movement from xRotation(Subtract for invert movement)
  56.         xRotation = Mathf.Clamp(xRotation, -30, 15); //Clamp rotation to prevent backflip
  57.         cam.localRotation = Quaternion.Euler(xRotation, transform.localRotation.y, transform.rotation.z); //Apply xRotation to camera rotation
  58.  
  59.     }
  60.  
  61.  
  62. }
  63.  
Add Comment
Please, Sign In to add comment