extends Control

var pressed: bool = false
var previous_position : Vector2 = Vector2.ZERO
var speed : float = 0.5
var delta_position: Vector2 = Vector2.ZERO
var damping_factor: float = 0.08

func _process(delta: float) -> void:
	simulate_joystick_motion(JOY_AXIS_RIGHT_X, delta_position.x * delta * speed, 0)
	delta_position *= (1 - damping_factor)

func _gui_input(event: InputEvent) -> void:
	# Filter touch or drag events only.
	if event is not InputEventScreenTouch and event is not InputEventScreenDrag:
		return

	if event is InputEventScreenTouch:
		if event.is_pressed():
			previous_position = event.position
			pressed = true
		else:
			pressed = false
			simulate_joystick_motion(JOY_AXIS_RIGHT_X, 0, 0)
			previous_position = Vector2.ZERO

	if pressed and event is InputEventScreenDrag:
		delta_position = clamp(previous_position - event.position, Vector2(-10, -10), Vector2(10, 10))
		
		# finally update the previous position
		previous_position = event.position

func simulate_joystick_motion(axis: int, value: float, device_id: int = 0) -> void:
	var joystick_event = InputEventJoypadMotion.new()
	joystick_event.device = device_id 
	joystick_event.axis = axis  # Axis index (e.g., 0 for X-axis, 1 for Y-axis)
	joystick_event.axis_value = value  # Value of the axis, typically between -1 and 1

	Input.parse_input_event(joystick_event)  # Process the event
