SphereDragController.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using UnityEngine;
  2. namespace Kamgam.SkyClouds
  3. {
  4. public class SphereDragController : MonoBehaviour
  5. {
  6. private Vector3 _initialPosition;
  7. private bool _isDragging = false;
  8. private Vector3 _offset;
  9. void Start()
  10. {
  11. _initialPosition = transform.position;
  12. }
  13. void Update()
  14. {
  15. // Start dragging
  16. if (Input.GetMouseButtonDown(0))
  17. {
  18. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  19. RaycastHit[] hits = Physics.RaycastAll(ray);
  20. foreach (RaycastHit hit in hits)
  21. {
  22. // Check if collider is child of this.
  23. if (hit.collider.transform == transform)
  24. {
  25. _isDragging = true;
  26. _offset = transform.position - hit.point;
  27. break;
  28. }
  29. }
  30. }
  31. // Stop dragging
  32. if (Input.GetMouseButtonUp(0))
  33. {
  34. _isDragging = false;
  35. }
  36. // Dragging
  37. if (_isDragging)
  38. {
  39. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  40. Plane dragPlane = new Plane(Vector3.up, _initialPosition);
  41. if (dragPlane.Raycast(ray, out float distance))
  42. {
  43. Vector3 hitPoint = ray.GetPoint(distance) + _offset;
  44. transform.position = new Vector3(hitPoint.x, _initialPosition.y, hitPoint.z);
  45. }
  46. }
  47. }
  48. }
  49. }