ETFXMouseOrbit.cs 2.5 KB

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