|
| 1 | +extends Node |
| 2 | + |
| 3 | +var current = null |
| 4 | +var drag_offset = Vector2() |
| 5 | + |
| 6 | +var candidates = [] |
| 7 | + |
| 8 | +export var drag_group = "draggable" |
| 9 | + |
| 10 | + |
| 11 | +func _ready(): |
| 12 | + var draggables = get_tree().get_nodes_in_group(drag_group) |
| 13 | + for dragable in draggables: |
| 14 | + if dragable is CollisionObject2D: |
| 15 | + dragable.connect("mouse_entered",self,"mouse_entered",[dragable]) |
| 16 | + dragable.connect("mouse_exited",self,"mouse_exited",[dragable]) |
| 17 | + dragable.connect("input_event",self,"input_event",[dragable]) |
| 18 | + |
| 19 | +func _process(delta): |
| 20 | + if current is Node2D: |
| 21 | + current.global_position = current.get_global_mouse_position() - drag_offset |
| 22 | + |
| 23 | +func mouse_entered(which): |
| 24 | + candidates.append(which) |
| 25 | + pass |
| 26 | + |
| 27 | +func mouse_exited(which): |
| 28 | + candidates.erase(which) |
| 29 | + pass |
| 30 | + |
| 31 | +func input_event(viewport: Node, event: InputEvent, shape_idx: int,which:Node2D): |
| 32 | + if event is InputEventMouseButton and event.button_index == BUTTON_LEFT: |
| 33 | + if event.is_pressed(): |
| 34 | + candidates.sort_custom(self,"depth_sort") |
| 35 | + var last = candidates.back() |
| 36 | + if last: |
| 37 | + last.raise() |
| 38 | + current = last |
| 39 | + drag_offset = current.get_global_mouse_position() - current.global_position |
| 40 | + if current.has_method("on_drag_start"): |
| 41 | + current.on_drag_start() |
| 42 | + else: |
| 43 | + var can_drop = true |
| 44 | + if current: |
| 45 | + if current.has_method("on_drop"): |
| 46 | + var on_drop_result = current.on_drop() |
| 47 | + can_drop = on_drop_result == null || on_drop_result |
| 48 | + if can_drop: |
| 49 | + current = null |
| 50 | + |
| 51 | +func depth_sort(a,b): |
| 52 | + return b.get_index()<a.get_index() |
0 commit comments