108 lines
2.3 KiB
GDScript3
108 lines
2.3 KiB
GDScript3
|
extends CharacterBody2D
|
||
|
|
||
|
@export var locked := false:
|
||
|
set(val):
|
||
|
locked = val
|
||
|
if locked:
|
||
|
listening = false
|
||
|
dragging = false
|
||
|
mouse_inside = false
|
||
|
if is_node_ready():
|
||
|
$CollisionShape2D.disabled = locked
|
||
|
@export var label_text := "角":
|
||
|
set(val):
|
||
|
label_text = val
|
||
|
if is_node_ready():
|
||
|
$Label.text = label_text
|
||
|
@export var boundart_rect := Rect2(0, 0, 1000, 1000)
|
||
|
|
||
|
static var occupied := false
|
||
|
static var mutex := Mutex.new()
|
||
|
var target_position := Vector2()
|
||
|
|
||
|
# draggable
|
||
|
var listening := false
|
||
|
var mouse_inside := false
|
||
|
var dragging := false:
|
||
|
set(val):
|
||
|
if dragging == val:
|
||
|
return
|
||
|
var success = false
|
||
|
if val:
|
||
|
mutex.lock()
|
||
|
dragging = !occupied
|
||
|
if dragging:
|
||
|
success = true
|
||
|
occupied = true
|
||
|
Input.set_default_cursor_shape(Input.CURSOR_DRAG)
|
||
|
mutex.unlock()
|
||
|
else:
|
||
|
mutex.lock()
|
||
|
if dragging:
|
||
|
dragging = false
|
||
|
occupied = false
|
||
|
Input.set_default_cursor_shape(Input.CURSOR_ARROW)
|
||
|
mutex.unlock()
|
||
|
if success:
|
||
|
_move_front()
|
||
|
|
||
|
|
||
|
func _ready():
|
||
|
$CollisionShape2D.disabled = locked
|
||
|
$Label.text = label_text
|
||
|
target_position = global_position
|
||
|
mouse_entered.connect(_on_mouse_entered)
|
||
|
mouse_exited.connect(_on_mouse_exited)
|
||
|
|
||
|
|
||
|
func _move_front():
|
||
|
var parent = get_parent()
|
||
|
if not parent:
|
||
|
return
|
||
|
parent.move_child(self, parent.get_child_count() - 1)
|
||
|
|
||
|
|
||
|
func _on_mouse_entered():
|
||
|
listening = true
|
||
|
mouse_inside = true
|
||
|
|
||
|
|
||
|
func _on_mouse_exited():
|
||
|
mouse_inside = false
|
||
|
if not dragging:
|
||
|
listening = false
|
||
|
|
||
|
|
||
|
func _physics_process(_delta: float) -> void:
|
||
|
if not locked and not dragging:
|
||
|
move_and_slide()
|
||
|
_clamp_position()
|
||
|
target_position = position
|
||
|
|
||
|
|
||
|
func _unhandled_input(event: InputEvent) -> void:
|
||
|
if locked or not listening:
|
||
|
return
|
||
|
if event is InputEventMouseButton:
|
||
|
if event.button_index == MOUSE_BUTTON_LEFT:
|
||
|
if dragging and not mouse_inside:
|
||
|
listening = false
|
||
|
dragging = false
|
||
|
else:
|
||
|
dragging = event.pressed
|
||
|
|
||
|
if dragging and event is InputEventMouseMotion:
|
||
|
var new_pos = event.position
|
||
|
target_position = new_pos
|
||
|
position = target_position
|
||
|
_clamp_position()
|
||
|
|
||
|
|
||
|
func _clamp_position():
|
||
|
position.x = clamp(
|
||
|
position.x, boundart_rect.position.x, boundart_rect.position.x + boundart_rect.size.x
|
||
|
)
|
||
|
position.y = clamp(
|
||
|
position.y, boundart_rect.position.y, boundart_rect.position.y + boundart_rect.size.y
|
||
|
)
|