Advertisement
Guest User

eidodragscriptv2

a guest
May 25th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [RequireComponent(typeof(Camera))]
  5. public class ObjectDragging : MonoBehaviour
  6. {
  7. private GameObject draggedObject;
  8.  
  9. private Rigidbody draggedObjectRigidbody;
  10.  
  11. private GameObject oldParent;
  12.  
  13. private bool objectHeld;
  14.  
  15. private Transform originPoint;
  16.  
  17. private new Camera camera;
  18.  
  19. void Start()
  20. {
  21. camera = GetComponent<Camera>();
  22. }
  23.  
  24. void Update ()
  25. {
  26. CheckForGrab();
  27. ReticleCheck();
  28. }
  29.  
  30. void CheckForGrab()
  31. {
  32. if (Input.GetKeyDown(KeyCode.Mouse0))
  33. {
  34. if (!objectHeld)
  35. GrabObject();
  36. else
  37. DropObject();
  38. }
  39. }
  40.  
  41. void ReticleCheck()
  42. {
  43. if (objectHeld)
  44. {
  45. Ray ray = camera.ScreenPointToRay(new Vector3(camera.pixelWidth / 2, camera.pixelHeight / 2));
  46. RaycastHit hit;
  47. if (Physics.Raycast(ray, out hit) && hit.transform.tag != "Draggable")
  48. {
  49. DropObject();
  50. }
  51. }
  52. }
  53.  
  54. void GrabObject()
  55. {
  56. if (!objectHeld)
  57. {
  58. Ray ray = camera.ScreenPointToRay(new Vector3(camera.pixelWidth / 2, camera.pixelHeight / 2));
  59. RaycastHit hit;
  60. if (Physics.Raycast(ray, out hit) && hit.transform.tag == "Draggable")
  61. {
  62. if (hit.distance > 5)
  63. return;
  64.  
  65. objectHeld = true;
  66. draggedObject = hit.transform.gameObject;
  67.  
  68. draggedObjectRigidbody = draggedObject.GetComponent<Rigidbody>();
  69. draggedObjectRigidbody.useGravity = false;
  70. draggedObjectRigidbody.drag = 10;
  71.  
  72. oldParent = draggedObject.transform.parent.gameObject;
  73. draggedObject.transform.parent = this.transform;
  74.  
  75. }
  76. }
  77. }
  78.  
  79. void DropObject()
  80. {
  81. objectHeld = false;
  82.  
  83. draggedObjectRigidbody.useGravity = true;
  84. draggedObjectRigidbody.drag = 0;
  85.  
  86. draggedObject.transform.parent = oldParent.transform;
  87. }
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement