You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
3.0 KiB

  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. namespace UnityStandardAssets.Utility
  5. {
  6. public class DragRigidbody : MonoBehaviour
  7. {
  8. const float k_Spring = 50.0f;
  9. const float k_Damper = 5.0f;
  10. const float k_Drag = 10.0f;
  11. const float k_AngularDrag = 5.0f;
  12. const float k_Distance = 0.2f;
  13. const bool k_AttachToCenterOfMass = false;
  14. private SpringJoint m_SpringJoint;
  15. private void Update()
  16. {
  17. // Make sure the user pressed the mouse down
  18. if (!Input.GetMouseButtonDown(0))
  19. {
  20. return;
  21. }
  22. var mainCamera = FindCamera();
  23. // We need to actually hit an object
  24. RaycastHit hit = new RaycastHit();
  25. if (
  26. !Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition).origin,
  27. mainCamera.ScreenPointToRay(Input.mousePosition).direction, out hit, 100,
  28. Physics.DefaultRaycastLayers))
  29. {
  30. return;
  31. }
  32. // We need to hit a rigidbody that is not kinematic
  33. if (!hit.rigidbody || hit.rigidbody.isKinematic)
  34. {
  35. return;
  36. }
  37. if (!m_SpringJoint)
  38. {
  39. var go = new GameObject("Rigidbody dragger");
  40. Rigidbody body = go.AddComponent<Rigidbody>();
  41. m_SpringJoint = go.AddComponent<SpringJoint>();
  42. body.isKinematic = true;
  43. }
  44. m_SpringJoint.transform.position = hit.point;
  45. m_SpringJoint.anchor = Vector3.zero;
  46. m_SpringJoint.spring = k_Spring;
  47. m_SpringJoint.damper = k_Damper;
  48. m_SpringJoint.maxDistance = k_Distance;
  49. m_SpringJoint.connectedBody = hit.rigidbody;
  50. StartCoroutine("DragObject", hit.distance);
  51. }
  52. private IEnumerator DragObject(float distance)
  53. {
  54. var oldDrag = m_SpringJoint.connectedBody.drag;
  55. var oldAngularDrag = m_SpringJoint.connectedBody.angularDrag;
  56. m_SpringJoint.connectedBody.drag = k_Drag;
  57. m_SpringJoint.connectedBody.angularDrag = k_AngularDrag;
  58. var mainCamera = FindCamera();
  59. while (Input.GetMouseButton(0))
  60. {
  61. var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
  62. m_SpringJoint.transform.position = ray.GetPoint(distance);
  63. yield return null;
  64. }
  65. if (m_SpringJoint.connectedBody)
  66. {
  67. m_SpringJoint.connectedBody.drag = oldDrag;
  68. m_SpringJoint.connectedBody.angularDrag = oldAngularDrag;
  69. m_SpringJoint.connectedBody = null;
  70. }
  71. }
  72. private Camera FindCamera()
  73. {
  74. if (GetComponent<Camera>())
  75. {
  76. return GetComponent<Camera>();
  77. }
  78. return Camera.main;
  79. }
  80. }
  81. }