FineNerds

Orbit Camera

Jan 30th, 2017
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. namespace Controller
  5. {
  6.     public class Controller_Camera : MonoBehaviour {
  7.        
  8.         public Transform viewTarget;
  9.         public GameObject go;
  10.  
  11.         private Vector3 viewTarget_Orig;
  12.  
  13.         public float distance = 5.0f;
  14.         public float maxDistance = 20f;
  15.         public float minDistance = 0.6f;
  16.         public float rotSpeed = 100f;
  17.         public float panSpeed = 0.25f;
  18.         public float zoomSpeed = 0.25f;
  19.  
  20.         public int yMinLimit = -80;
  21.         public int yMaxLimit = 80;
  22.  
  23.         private float xDeg = 0.0f;
  24.         private float yDeg = 0.0f;
  25.  
  26.         float x = 0;
  27.         float y = 0;
  28.         float z = 0;
  29.        
  30.         void OnEnable() { init(); }
  31.  
  32.         public void init()
  33.         {
  34.             if(!viewTarget)
  35.             {
  36.                 if(!go)
  37.                     go = new GameObject("Cam Target");
  38.                 go.transform.position = transform.position + (transform.forward * distance);
  39.                 viewTarget = go.transform;
  40.                 viewTarget_Orig = viewTarget.position;
  41.             }
  42.  
  43.             distance = Vector3.Distance(transform.position, viewTarget.position);
  44.  
  45.             xDeg = Vector3.Angle(Vector3.right, transform.right);
  46.             yDeg = Vector3.Angle(Vector3.up, transform.up);
  47.         }
  48.  
  49.         private void FixedUpdate()
  50.         {
  51.             transform.LookAt(viewTarget);
  52.         }
  53.  
  54.         void LateUpdate() {
  55.  
  56.             x += Input.GetAxis("Mouse X") * rotSpeed * 0.02f;
  57.             y -= Input.GetAxis("Mouse Y") * rotSpeed * 0.02f;
  58.  
  59.             y = ClampAngle(y, yMinLimit, yMaxLimit);
  60.  
  61.             var rotation = Quaternion.Euler(y, x, z);
  62.             var position = rotation * new Vector3(0.0f, 0.0f, -distance) + viewTarget.position; //Suspected Cause
  63.             transform.rotation = rotation;
  64.             transform.position = position;
  65.         }
  66.  
  67.         static float ClampAngle(float angle , float min, float max)
  68.         {
  69.             if (angle < -360)
  70.                 angle += 360;
  71.             if (angle > 360)
  72.                 angle -= 360;
  73.             return Mathf.Clamp(angle, min, max);
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment