MouseForce.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Shatter Toolkit
  2. // Copyright 2015 Gustav Olsson
  3. using UnityEngine;
  4. namespace ShatterToolkit.Helpers
  5. {
  6. public class MouseForce : MonoBehaviour
  7. {
  8. public float impulseScale = 25.0f;
  9. protected Rigidbody grabBody;
  10. protected Vector3 grabPoint;
  11. protected float grabDistance;
  12. public void Update()
  13. {
  14. GrabBody();
  15. ReleaseBody();
  16. }
  17. public void FixedUpdate()
  18. {
  19. MoveBody();
  20. }
  21. protected void GrabBody()
  22. {
  23. if (grabBody == null)
  24. {
  25. // Let the player grab a rigidbody
  26. if (Input.GetMouseButtonDown(0))
  27. {
  28. RaycastHit hit;
  29. if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
  30. {
  31. if (hit.rigidbody != null)
  32. {
  33. grabBody = hit.rigidbody;
  34. grabPoint = grabBody.transform.InverseTransformPoint(hit.point);
  35. grabDistance = hit.distance;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. protected void ReleaseBody()
  42. {
  43. if (grabBody != null)
  44. {
  45. // Let the player release the rigidbody
  46. if (Input.GetMouseButtonUp(0))
  47. {
  48. grabBody = null;
  49. }
  50. }
  51. }
  52. protected void MoveBody()
  53. {
  54. if (grabBody != null)
  55. {
  56. // Move the grabbed rigidbody
  57. Vector3 screenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, grabDistance);
  58. Vector3 targetPoint = Camera.main.ScreenToWorldPoint(screenPoint);
  59. Vector3 anchorPoint = grabBody.transform.TransformPoint(grabPoint);
  60. Debug.DrawLine(targetPoint, anchorPoint, Color.red);
  61. Vector3 impulse = (targetPoint - anchorPoint) * (impulseScale * Time.fixedDeltaTime);
  62. grabBody.AddForceAtPosition(impulse, anchorPoint, ForceMode.Impulse);
  63. }
  64. }
  65. }
  66. }