extends Area3D

class_name DraggableObject

signal drag_started
signal drag_ended

var mouse_in: bool = false
var dragged: bool = false

func _mouse_enter() -> void:
	mouse_in = true

func _mouse_exit() -> void:
	mouse_in = false

func _process(_delta: float) -> void:
	if dragged == false:
		return
	var camera: Camera3D = get_viewport().get_camera_3d()
	var new_position: Vector3 = camera.project_position(get_viewport().get_mouse_position(),(-camera.basis.z).dot(camera.to_local(global_position)))
	global_position = new_position

func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if mouse_in and event.pressed:
			dragged = true
			drag_started.emit()
		if event.pressed == false:
			dragged = false
			drag_ended.emit()
