Created
August 29, 2024 13:26
-
-
Save deevus/d76331784ae3f782bcf46718bde7991a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends TouchScreenButton | |
@onready var indicator: Sprite2D = $Indicator | |
@onready var stick_center: Vector2 = texture_normal.get_size() / 2 | |
@onready var max_distance: float = texture_normal.get_size().x / 2 | |
@export_range(0.0, 0.5, 0.01) var deadzone := 0.1 | |
@export_range(0.1, 10.0) var smoothing := 2.0 | |
@export var x_axis: JoyAxis = JOY_AXIS_LEFT_X | |
@export var y_axis: JoyAxis = JOY_AXIS_LEFT_Y | |
@export var invert_x_axis: bool = false | |
@export var invert_y_axis: bool = false | |
var active: bool = false | |
func _process(_delta: float) -> void: | |
if active: | |
indicator.global_position = get_global_mouse_position() | |
indicator.position = (indicator.position - stick_center).limit_length(max_distance) | |
var x_axis_value: float = ( | |
signf(indicator.position.x) * pow(absf(indicator.position.x / max_distance), smoothing) | |
) | |
if invert_x_axis: | |
x_axis_value *= -1 | |
var y_axis_value: float = ( | |
signf(indicator.position.y) * pow(absf(indicator.position.y / max_distance), smoothing) | |
) | |
if invert_y_axis: | |
y_axis_value *= -1 | |
_simulate_joypad_x_axis(x_axis_value) | |
_simulate_joypad_y_axis(y_axis_value) | |
func _simulate_joypad_input(axis: JoyAxis, axis_value: float) -> void: | |
var input_action := InputEventJoypadMotion.new() | |
input_action.axis = axis | |
input_action.axis_value = axis_value | |
Input.parse_input_event(input_action) | |
func _simulate_joypad_x_axis(axis_value: float) -> void: | |
_simulate_joypad_input(x_axis, axis_value) | |
func _simulate_joypad_y_axis(axis_value: float) -> void: | |
_simulate_joypad_input(y_axis, axis_value) | |
func get_joystick_vector() -> Vector2: | |
return indicator.position | |
func _on_pressed() -> void: | |
active = true | |
func _on_released() -> void: | |
active = false | |
indicator.position = Vector2.ZERO | |
_simulate_joypad_x_axis(0) | |
_simulate_joypad_y_axis(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment