extends CharacterBody3D

var input3D : Vector3

@export var SPEED = 1.4
@export var SPRINT_SPEED = 3.0
@export var JUMP_VELOCITY = 4.5

var speed = .0

@onready var camera : Camera3D = get_viewport().get_camera_3d()

var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

func _ready():
	process_priority = 2

func getCameraRelativeInput() -> Vector3 :
	var cam_basis = camera.global_transform.basis
	cam_basis.x.y = 0
	cam_basis.x = cam_basis.x.normalized()
	cam_basis.z.y = 0
	cam_basis.z = cam_basis.z.normalized()

	var input = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	var relativeInput = Vector3.ZERO
	relativeInput += input.x * cam_basis.x
	relativeInput += input.y * cam_basis.z

	return relativeInput

func _physics_process(delta):
	if not is_on_floor():
		velocity.y -= gravity * delta

	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	input3D = getCameraRelativeInput()

	speed = SPEED + Input.get_action_strength("sprint") * SPRINT_SPEED

	var direction = input3D.normalized()
	if direction:
		velocity.x = direction.x * speed
		velocity.z = direction.z * speed
		look_at(direction + global_position)
	else:
		velocity.x = move_toward(velocity.x, 0, speed)
		velocity.z = move_toward(velocity.z, 0, speed)

	move_and_slide()
