PolygonOrbit.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEngine;
  2. using System.Collections;
  3. [AddComponentMenu("Camera-Control/Mouse drag Orbit with zoom")]
  4. public class PolygonOrbit : MonoBehaviour
  5. {
  6. public Transform target;
  7. public float distance = 5.0f;
  8. public float xSpeed = 120.0f;
  9. public float ySpeed = 120.0f;
  10. public float yMinLimit = -20f;
  11. public float yMaxLimit = 80f;
  12. public float distanceMin = .5f;
  13. public float distanceMax = 15f;
  14. public float smoothTime = 2f;
  15. float rotationYAxis = 0.0f;
  16. float rotationXAxis = 0.0f;
  17. float velocityX = 0.0f;
  18. float velocityY = 0.0f;
  19. // Use this for initialization
  20. void Start()
  21. {
  22. Vector3 angles = transform.eulerAngles;
  23. rotationYAxis = angles.y;
  24. rotationXAxis = angles.x;
  25. // Make the rigid body not change rotation
  26. if (GetComponent<Rigidbody>())
  27. {
  28. GetComponent<Rigidbody>().freezeRotation = true;
  29. }
  30. }
  31. void LateUpdate()
  32. {
  33. if (target)
  34. {
  35. if (Input.GetMouseButton(1))
  36. {
  37. velocityX += xSpeed * Input.GetAxis("Mouse X") * distance * 0.02f;
  38. velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
  39. }
  40. rotationYAxis += velocityX;
  41. rotationXAxis -= velocityY;
  42. rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
  43. //Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
  44. Quaternion toRotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
  45. Quaternion rotation = toRotation;
  46. distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);
  47. RaycastHit hit;
  48. if (Physics.Linecast(target.position, transform.position, out hit))
  49. {
  50. distance -= hit.distance;
  51. }
  52. Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
  53. Vector3 position = rotation * negDistance + target.position;
  54. transform.rotation = rotation;
  55. transform.position = position;
  56. velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
  57. velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
  58. }
  59. }
  60. public static float ClampAngle(float angle, float min, float max)
  61. {
  62. if (angle < -360F)
  63. angle += 360F;
  64. if (angle > 360F)
  65. angle -= 360F;
  66. return Mathf.Clamp(angle, min, max);
  67. }
  68. }