Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(Camera))]
- public class CamOrbiting : MonoBehaviour
- {
- public Transform targetMesh;
- public float distance = 10f;
- public float zoomSpeed = 2f;
- public float orbitSpeed = 100f;
- public float panSpeed = 0.01f;
- public float minZoom = 1f;
- public float maxZoom = 100f;
- Vector3 orbitCenter;
- float yaw = 0f;
- float pitch = 20f;
- Camera m_cam;
- void Start()
- {
- m_cam = GetComponent<Camera>();
- if (targetMesh != null)
- {
- orbitCenter = GetMeshBoundsCenter(targetMesh);
- }
- }
- void Update()
- {
- HandleOrbit();
- HandlePan();
- HandleZoom();
- }
- void HandleOrbit()
- {
- if (Input.GetMouseButton(0)) // rotate with left click
- {
- yaw += Input.GetAxis("Mouse X") * orbitSpeed * Time.unscaledDeltaTime;// unscaled delta time in case you're using it in a paused menu
- pitch -= Input.GetAxis("Mouse Y") * orbitSpeed * Time.unscaledDeltaTime;
- pitch = Mathf.Clamp(pitch, -89f, 89f);
- }
- Quaternion rotation = Quaternion.Euler(pitch, yaw, 0f);
- Vector3 direction = rotation * Vector3.forward;
- transform.position = orbitCenter - direction * distance;
- transform.rotation = rotation;
- }
- void HandlePan()
- {
- if (Input.GetMouseButton(2)) // pan with middle mouse button
- {
- float panX = -Input.GetAxis("Mouse X") * panSpeed * m_cam.orthographicSize;
- float panY = -Input.GetAxis("Mouse Y") * panSpeed * m_cam.orthographicSize;
- // move orbit center based on camera right and up
- Vector3 right = transform.right;
- Vector3 up = transform.up;
- orbitCenter += right * panX + up * panY;
- }
- }
- void HandleZoom()
- {
- float scroll = Input.GetAxis("Mouse ScrollWheel");
- m_cam.orthographicSize -= scroll * zoomSpeed;
- m_cam.orthographicSize = Mathf.Clamp(m_cam.orthographicSize, minZoom, maxZoom);
- }
- Vector3 GetMeshBoundsCenter(Transform target)
- {
- var renderers = target.GetComponentsInChildren<Renderer>();
- if (renderers.Length == 0) return target.position;
- Bounds combinedBounds = renderers[0].bounds;
- for (int i = 1; i < renderers.Length; i++)
- {
- combinedBounds.Encapsulate(renderers[i].bounds);
- }
- return combinedBounds.center;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment