1. using UnityEngine;
  2. using UnityEngine;
  3. using System.Collections;
  4. public class DragMouseOrbit : MonoBehaviour
  5. {
  6. public Transform target;
  7. public float distance = 2.0f;
  8. public float xSpeed = 20.0f;
  9. public float ySpeed = 20.0f;
  10. public float yMinLimit = -90f;
  11. public float yMaxLimit = 90f;
  12. public float distanceMin = 10f;
  13. public float distanceMax = 10f;
  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(0))
  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. }




from https://answers.unity.com/questions/1257281/how-to-rotate-camera-orbit-around-a-game-object-on.html

+ Recent posts