This is my code for joystick:
extends TouchScreenButton
var camerapos = Vector2()#variable for position of camera
var adjustpos
var touchpos
var dirpos
var eventpos
var evenpos
var ready
#variable for resting position of joystick with camera position taken into account
# Declare member variables here. Examples:
# var a = 2
# var b = "text"
# Called when the node enters the scene tree for the first time.
func _ready():
ready2()
func _input(event):
if ready != null:
touchpos = event.position + (camerapos - Vector2(480, 320))
if event is InputEventScreenDrag:
if touchpos.distance_to(adjustpos) > 80:
evenpos = event.position - Vector2(160, 480)
eventpos = evenpos.normalized()*80
global_position = eventpos.normalized()*80 + Vector2(camerapos.x - 320, camerapos.y +160)
else:
global_position = touchpos
eventpos = event.position - Vector2(160, 480)
else:
global_position = Vector2(camerapos.x - 320, camerapos.y + 160)
eventpos = Vector2(0, 0)
func ready2():
if camerapos != null:
global_position = Vector2(camerapos.x - 320, camerapos.y + 160)
ready = 1
func _process(delta):
if ready != null:
if touchpos != null and adjustpos != null:
if touchpos.distance_to(adjustpos) < 80:
global_position = touchpos
eventpos = touchpos
if touchpos.distance_to(adjustpos) > 80:
global_position = eventpos.normalized()*80 + Vector2(camerapos.x - 320, camerapos.y +160)
camerapos = Main.camerapos #sets the camerapos variable to camera position
adjustpos = Vector2(camerapos.x - 320, camerapos.y + 160)
dirpos = global_position - adjustpos
This is my code for player.
extends KinematicBody2D
export var speed = 0.5
var pos = Vector2()
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pos = Main.pos #main.pos = eventpos
if pos != null:
move_and_slide(pos*speed)
Here is a video on my phone of it working properly
