Node2D.gd:
1 extends Node2D 2 3 var ball = preload("res://Area2D.tscn") 4 var prv 5 onready var viewSize = get_viewport_rect().size 6 7 class Sorter: 8 static func sort(a, b): 9 if a["collider"].get_index() > b["collider"].get_index(): 10 return true 11 return false 12 13 func _ready(): 14 randomize() 15 for i in 200: 16 new(i > 100) 17 18 func _input(event): 19 if event is InputEventMouseButton: 20 match event.button_index: 21 BUTTON_LEFT: 22 if event.is_pressed(): 23 #这里可以应用各种规则来提高效率,比如减少intersect_point检测数量,减少intersect_point触发次数 24 var stime = OS.get_ticks_msec() 25 var shapes = get_world_2d().direct_space_state.intersect_point(get_global_mouse_position(), 9999, [], 0x7fffffff, false, true) 26 var size = shapes.size() 27 if size > 0: 28 if size > 1: 29 shapes.sort_custom(Sorter, "sort") 30 var etime = OS.get_ticks_msec() - stime 31 print("检测耗时(毫秒)", etime) 32 var collider = shapes[0]["collider"] 33 if collider.has_method("_on_drag"): 34 if collider.get_index() < collider.get_parent().get_child_count() - 1: 35 collider.raise() 36 print("置顶", collider.get_instance_id()) 37 prv = collider 38 collider._on_drag(true) 39 else: 40 print("intersect_point zero") 41 else: 42 if prv: 43 prv._on_drag(false) 44 prv = null 45 BUTTON_RIGHT: 46 if event.is_pressed(): 47 new(false) 48 49 func new(rnd): 50 var node = ball.instance() 51 var size = node.get_node("Sprite").texture.get_size() 52 if rnd: 53 node.position = Vector2(rand_range(size.x * 4, viewSize.x - size.x), rand_range(size.y, viewSize.y - size.y)) 54 else: 55 node.position = size 56 add_child(node)
Area2D.gd:
1 extends Area2D 2 3 var isDrag = false 4 var offset 5 onready var label = $Label 6 onready var sprite = $Sprite 7 onready var id = self.get_instance_id() 8 9 func _ready(): 10 label.text = str(id); 11 sprite.self_modulate = Color(randf(), randf(), randf(), 1) 12 13 func _process(delta): 14 if isDrag: 15 self.position = get_global_mouse_position() + offset 16 17 func _on_drag(state): 18 if state: 19 offset = self.position - get_global_mouse_position() 20 isDrag = true 21 print("开始拖动", id) 22 else: 23 if isDrag: 24 isDrag = false 25 print("结束拖动", id) 26 27 #func _on_Area2D_input_event(viewport, event, shape_idx): 28 # if isDrag: 29 # if event is InputEventMouseButton and event.button_index == BUTTON_LEFT: 30 # if not event.is_pressed(): 31 # isDrag = false 32 # print("内部结束(实例id)", id)