CameraOrbit.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using UnityEngine;
  3. namespace TDLN.CameraControllers
  4. {
  5. public class CameraOrbit : MonoBehaviour
  6. {
  7. public GameObject target;
  8. public float distance = 10.0f;
  9. public float xSpeed = 250.0f;
  10. public float ySpeed = 120.0f;
  11. public float yMinLimit = -20;
  12. public float yMaxLimit = 80;
  13. float x = 0.0f;
  14. float y = 0.0f;
  15. void Start()
  16. {
  17. var angles = transform.eulerAngles;
  18. x = angles.y;
  19. y = angles.x;
  20. }
  21. float prevDistance;
  22. void LateUpdate()
  23. {
  24. if (distance < 2) distance = 2;
  25. distance -= Input.GetAxis("Mouse ScrollWheel") * 2;
  26. if (target && (Input.GetMouseButton(0) || Input.GetMouseButton(1)))
  27. {
  28. var pos = Input.mousePosition;
  29. var dpiScale = 1f;
  30. if (Screen.dpi < 1) dpiScale = 1;
  31. if (Screen.dpi < 200) dpiScale = 1;
  32. else dpiScale = Screen.dpi / 200f;
  33. if (pos.x < 380 * dpiScale && Screen.height - pos.y < 250 * dpiScale) return;
  34. // comment out these two lines if you don't want to hide mouse curser or you have a UI button
  35. Cursor.visible = false;
  36. Cursor.lockState = CursorLockMode.Locked;
  37. x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
  38. y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
  39. y = ClampAngle(y, yMinLimit, yMaxLimit);
  40. var rotation = Quaternion.Euler(y, x, 0);
  41. var position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.transform.position;
  42. transform.rotation = rotation;
  43. transform.position = position;
  44. }
  45. else
  46. {
  47. // comment out these two lines if you don't want to hide mouse curser or you have a UI button
  48. Cursor.visible = true;
  49. Cursor.lockState = CursorLockMode.None;
  50. }
  51. if (Math.Abs(prevDistance - distance) > 0.001f)
  52. {
  53. prevDistance = distance;
  54. var rot = Quaternion.Euler(y, x, 0);
  55. var po = rot * new Vector3(0.0f, 0.0f, -distance) + target.transform.position;
  56. transform.rotation = rot;
  57. transform.position = po;
  58. }
  59. }
  60. static float ClampAngle(float angle, float min, float max)
  61. {
  62. if (angle < -360)
  63. angle += 360;
  64. if (angle > 360)
  65. angle -= 360;
  66. return Mathf.Clamp(angle, min, max);
  67. }
  68. }
  69. }