|
| 1 | +using System; |
| 2 | +using UnityEngine; |
| 3 | +using UnityEngine.InputSystem; |
| 4 | +using UnityEngine.InputSystem.EnhancedTouch; |
| 5 | +using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch; |
| 6 | + |
| 7 | +public class OnMouseEventDragSample : MonoBehaviour |
| 8 | +{ |
| 9 | + private Vector3 screenPoint; |
| 10 | + private Vector3 offset; |
| 11 | + |
| 12 | + private Vector3 startPosition; |
| 13 | + private bool wasDragging => Vector3.Distance(startPosition, transform.position) > 0.01f; |
| 14 | + private bool selected; |
| 15 | + |
| 16 | + // This logic starts the drag operation and safes the offset of the object position to the cursor position, to preserve the relative position. |
| 17 | + void OnMouseDown() |
| 18 | + { |
| 19 | + if (Pointer.current == null) |
| 20 | + return; |
| 21 | + |
| 22 | + screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); |
| 23 | + float x = Pointer.current.position.x.value; |
| 24 | + float y = Pointer.current.position.y.value; |
| 25 | + offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(x, y, screenPoint.z)); |
| 26 | + startPosition = transform.position; |
| 27 | + } |
| 28 | + |
| 29 | + // This logic allows dragging the object. |
| 30 | + void OnMouseDrag() |
| 31 | + { |
| 32 | + if (Pointer.current == null) |
| 33 | + return; |
| 34 | + |
| 35 | + Vector3 curScreenPoint = new Vector3(Pointer.current.position.x.value, Pointer.current.position.y.value, screenPoint.z); |
| 36 | + Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset; |
| 37 | + transform.position = curPosition; |
| 38 | + } |
| 39 | + |
| 40 | + // This can be used to select objects. This logic allows dragging without selection. |
| 41 | + private void OnMouseUp() |
| 42 | + { |
| 43 | + if (wasDragging) |
| 44 | + return; |
| 45 | + |
| 46 | + selected = !selected; |
| 47 | + gameObject.GetComponent<Renderer>().material.SetColor("_Color", !selected ? Color.blue : Color.white); |
| 48 | + } |
| 49 | +} |
0 commit comments