using System.Collections; using System.Collections.Generic; using UnityEngine; public class OrbitCamera : MonoBehaviour { public GameObject target; public float speedX = 1000; public float speedY = 1000; public float minTheta = 0; public float maxTheta = 89; private float distance = 0; private float phi = 0; private float theta = 0; private float yOffset = 0; // Start is called before the first frame update void Start() { // Calculate initial distance and position offset if (distance == 0) { Vector3 delta = transform.position - target.transform.position; yOffset = delta.y; delta.y = 0; distance = delta.magnitude; } UpdatePos(); } // Update is called once per frame void Update() { if (Input.GetMouseButton(0)) { phi = phi - speedX * Time.deltaTime * Input.GetAxis("Mouse X"); while (phi < 0) phi += 360; while (phi > 360) phi -= 360; theta = Mathf.Clamp(theta - speedY * Time.deltaTime * Input.GetAxis("Mouse Y"), Mathf.Max(minTheta, -89), Mathf.Min(maxTheta, 89)); } UpdatePos(); } private void UpdatePos() { Vector3 pos = target.transform.position; pos.x = distance * Mathf.Cos(theta * Mathf.Deg2Rad) * Mathf.Sin(phi * Mathf.Deg2Rad); pos.y = yOffset + distance * Mathf.Sin(theta * Mathf.Deg2Rad); pos.z = -distance * Mathf.Cos(theta * Mathf.Deg2Rad) * Mathf.Cos(phi * Mathf.Deg2Rad); transform.position = target.transform.position + pos; transform.LookAt(target.transform.position + new Vector3(0, yOffset, 0)); } }