- Edited
I use v4.4.1.stable.official godot version.
I tried to use a TouchScreenButton node to create a joystick , two image : circle and a knob with this script into joystick2d_v001.tscn scene
@onready var knob: Sprite2D = $knob # Reference to the knob node
@onready var max_distance = shape.radius # Maximum distance the knob can move
@onready var knob_center: Vector2 = Vector2.ZERO # Dynamically calculated knob center
var touched: bool = false
func _ready() -> void:
# Calculate knob_center based on texture size and initialize the knob's position
knob_center = texture_normal.get_size() / 2
knob.position = knob_center # Ensure the knob starts at the center
set_process_input(true) # Enable input processing
func _process(_delta: float) -> void:
if touched:
# Restrict knob movement within the max_distance
knob.position = (knob.position - knob_center).limit_length(max_distance) + knob_center
else:
# Reset the knob to the center when touch ends
knob.position = knob_center
func _input(event: InputEvent) -> void:
if event is InputEventScreenTouch:
if event.pressed:
# Convert the input position from global to local coordinates
var local_touch_position = to_local(event.position)
if local_touch_position.distance_to(knob_center) <= max_distance:
touched = true
knob.position = local_touch_position
else:
touched = false # End touch
elif event is InputEventScreenDrag:
if touched:
# Convert drag position to local coordinates and restrict movement
var local_drag_position = to_local(event.position)
knob.position = (local_drag_position - knob_center).limit_length(max_distance) + knob_center
This is main scene script I used this script for the joystick scene but is freeze and not change position of knob , why ?
@onready var sprite_2d: Sprite2D = $Sprite2D # Reference to the sprite that moves
var joystick_scene: PackedScene = load("res://joystick2d_v001.tscn") # Path to joystick scene
var joystick_instance: TouchScreenButton
func _ready() -> void:
# Load and instantiate the joystick scene
if joystick_scene and joystick_scene is PackedScene:
joystick_instance = joystick_scene.instantiate() as TouchScreenButton
add_child(joystick_instance)
# Set joystick position relative to its parent node
joystick_instance.position = Vector2(200, 200) # Adjust position in the scene
print("Joystick successfully added.")
else:
print("Failed to load joystick scene!")
func _input(event: InputEvent) -> void:
if joystick_instance:
# Forward input events to the joystick
joystick_instance._input(event)
func _process(delta: float) -> void:
if joystick_instance:
# Calculate the joystick's directional input based on knob position
var joystick_position = joystick_instance.knob.position - joystick_instance.knob_center
# Move the sprite based on joystick input
if joystick_position.length() > 0:
sprite_2d.position += joystick_position.normalized() * delta * 200 # Adjust speed
print("Joystick Position: ", joystick_position)