monsterfangen/scripts/joystick.gd

66 lines
2.2 KiB
GDScript

extends Panel
@onready var talk_a_texture = preload("res://resources/textures/Xbox Series/Vector/xbox_button_a.svg")
@onready var drag_texture = preload("res://resources/textures/Generic/Vector/generic_button_circle.svg")
var thumbstick_size_factor = 0.5
@onready var thumbstick = $Thumbstick
var middle: Vector2 = Vector2(100, 100)
var touch_start: Vector2 = Vector2(0, 0)
var jump_threshold: float = 10.0
var previous: Vector2 = Vector2(0, 0)
var delta: float = 0.0
var pressed: bool = false
func _on_gui_input(event: InputEvent) -> void:
if event is not InputEventScreenTouch and event is not InputEventScreenDrag:
return
if event.is_pressed() == false:
simulate_joystick_motion(0, Vector2.ZERO.x)
simulate_joystick_motion(1, Vector2.ZERO.y)
thumbstick.position = middle - thumbstick.size / 2.0
thumbstick.texture = talk_a_texture
if event is InputEventScreenTouch and pressed == true:
Input.action_press("ui_select")
print("Talk")
pressed = false
if event is InputEventScreenTouch and event.is_pressed():
pressed = true
if event is InputEventScreenDrag:
# cancel the talking action
pressed = false
# swap to drag texture
thumbstick.texture = drag_texture
var touch_position = event.position
thumbstick.position = touch_position - thumbstick.size / 2.0
var delta = middle - touch_position
var direction = delta.normalized()
simulate_joystick_motion(0, -direction.x)
simulate_joystick_motion(1, -direction.y)
#if previous.y > thumbstick.position.y + jump_threshold:
# print("jump")
# Input.action_press("ui_accept")
#print(previous)
#previous = thumbstick.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
func _on_resized() -> void:
print("Size changed to %s" % size)
middle = size / 2.0
custom_minimum_size = Vector2(size.x, size.x)
thumbstick.custom_minimum_size = Vector2(size.x, size.x) * thumbstick_size_factor
thumbstick.position = middle - thumbstick.size / 2.0