Drag.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using UnityEngine;
  2. using System.Collections;
  3. [RequireComponent(typeof(BoxCollider2D))]
  4. public class Drag : MonoBehaviour {
  5. public GameObject target;
  6. public bool isMouseDrag = false;
  7. private Vector3 screenPosition;
  8. private Vector3 offset;
  9. // Update is called once per frame
  10. void Update()
  11. {
  12. if (Input.GetMouseButtonDown(0))
  13. {
  14. RaycastHit hitInfo;
  15. target = ReturnClickedObject(out hitInfo);
  16. if (target != null)
  17. {
  18. isMouseDrag = true;
  19. Debug.Log("target position :" + target.transform.position);
  20. //Convert world position to screen position.
  21. screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
  22. offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
  23. }
  24. }
  25. if (Input.GetMouseButtonUp(0))
  26. {
  27. isMouseDrag = false;
  28. }
  29. if (isMouseDrag)
  30. {
  31. //track mouse position.
  32. Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
  33. //convert screen position to world position with offset changes.
  34. Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
  35. //It will update target gameobject's current postion.
  36. target.transform.position = currentPosition;
  37. }
  38. }
  39. GameObject ReturnClickedObject(out RaycastHit hit)
  40. {
  41. GameObject target = null;
  42. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  43. if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
  44. {
  45. target = hit.collider.gameObject;
  46. }
  47. return target;
  48. }
  49. }