extends Node3D

const SENSETIVITY = 0.009;
var walk = 2
@onready var head = $"."
@onready var camera = $"./Camera"

func _ready():
	camera.make_current()
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)

func _unhandled_input(event):
	if Input.is_action_pressed("MWU"):
		walk += walk / 5.
		print("UP " + str(walk))
	if Input.is_action_pressed("MWD"):
		walk -= walk / 5.
		print("DOWN " + str(walk))
	walk = clamp(walk, 0.01, 15)
	if event is InputEventMouseMotion:
		head.rotate_y(-event.relative.x * SENSETIVITY)
		camera.rotate_x(-event.relative.y * SENSETIVITY)
		camera.rotation.x = clamp(camera.rotation.x, deg_to_rad(-90), deg_to_rad(90))

func _physics_process(delta):
	var input_dir = Input.get_vector("left", "right", "forward", "backward")
	#var direction = head.transform.rotation
	var direction = (head.transform.basis * Vector3(input_dir.x, input_dir.x, input_dir.y)).normalized()
	#var direction = (head.transform.basis * Vector2(input_dir.x, input_dir.y)).normalized()
	var velocity = Vector3.ZERO
	var speed
	
	if Input.is_action_pressed("run"):
		speed = walk * 2
	else:
		speed = walk
	velocity.y = Input.get_vector("crawl", "jump", "left", "right").x * speed
	if direction:
		velocity.x = direction.x * speed
		velocity.z = direction.z * speed
	else:
		velocity.x = lerp(velocity.x, direction.x * speed, delta * 4)
		velocity.z = lerp(velocity.z, direction.z * speed, delta * 4)
	head.position += velocity
