I used Godot version 3.0.6 to create a joystick scene for the game.
First, you need to activate the touch option from Project Settings – Display – Windows – Emulate Touchscreen.
This will allow you to use the touchscreen into your game.
Create a scene with the name Analog and add one CanvasLayer.
Rename the CanvasLayer to Analog and add a Sprite.
Rename the Sprite to Big and add to this a new Sprite and rename it Small.
Add textures to the Big and Small sprites to have a joystick on screen.
Create two scripts for Analog and Big with the same names.
Add this code source to the script Analog.gd:
1 2 3 4 5 | extends CanvasLayer var joystick_speed = 0; var joystick_angle = 0; var joystick_vector = Vector2(); |
The source code for Big.gd is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | extends Sprite const RADIUS = 75; const SMALL_RADIUS = 33; var joystick_pos; var evt_index = -1; func _init(): joystick_pos = position; func _input(event): if event is InputEventScreenTouch: if event.is_pressed(): if joystick_pos.distance_to(event.position) < RADIUS: evt_index = event.index elif evt_index != -1: if evt_index == event.index: evt_index = -1; $Small.position = Vector2(); $"../".joystick_vector = Vector2(); $"../".joystick_angle = 0; $"../".joystick_speed = 0; if evt_index != -1 and event is InputEventScreenDrag: var jdist = joystick_pos.distance_to(event.position); if jdist + SMALL_RADIUS > RADIUS: jdist = RADIUS - SMALL_RADIUS var jvect = (event.position - joystick_pos).normalized() var jang = event.position.angle_to_point(joystick_pos) $"../".joystick_vector = jvect; $"../".joystick_angle = jang; $"../".joystick_speed = jdist; # print values for jvect, jang and jdist create by joystick movement print(jvect,jang,jdist) $Small.position = jvect * jdist |
To use this joystick just add the scene to your player and import the variables like this:
1 2 | func move_player_joystick(delta): position += get_node("../Analog").joystick_vector*get_node("../Analog").joystick_speed * delta; |