Draggable.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using UnityEngine;
  2. public class Draggable : MonoBehaviour
  3. {
  4. public bool fixX;
  5. public bool fixY;
  6. public Transform thumb;
  7. bool dragging;
  8. void FixedUpdate()
  9. {
  10. if (Input.GetMouseButtonDown(0)) {
  11. dragging = false;
  12. var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  13. RaycastHit hit;
  14. if (GetComponent<Collider>().Raycast(ray, out hit, 100)) {
  15. dragging = true;
  16. }
  17. }
  18. if (Input.GetMouseButtonUp(0)) dragging = false;
  19. if (dragging && Input.GetMouseButton(0)) {
  20. var point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  21. point = GetComponent<Collider>().ClosestPointOnBounds(point);
  22. SetThumbPosition(point);
  23. SendMessage("OnDrag", Vector3.one - (thumb.position - GetComponent<Collider>().bounds.min) / GetComponent<Collider>().bounds.size.x);
  24. }
  25. }
  26. void SetDragPoint(Vector3 point)
  27. {
  28. point = (Vector3.one - point) * GetComponent<Collider>().bounds.size.x + GetComponent<Collider>().bounds.min;
  29. SetThumbPosition(point);
  30. }
  31. void SetThumbPosition(Vector3 point)
  32. {
  33. thumb.position = new Vector3(fixX ? thumb.position.x : point.x, fixY ? thumb.position.y : point.y, thumb.position.z);
  34. }
  35. }