extends CharacterBody3D

const SPEED = 5.0
const JUMP_VELOCITY = 4.5

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

@onready var cam_pointer = $camPointer
@onready var persone = $Persone

var direction := Vector3(0, 0, -1)
var lookDirection := Vector3(0, 0, -1)

func _ready():
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	persone.animation("idle")

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

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

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	#var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	#
	#input_dir = cam_pointer
	
	var dir: Vector3
	
	if Input.is_action_pressed("up"):
		dir = (transform.basis * direction)
	else:
		dir = Vector3()
	
	if dir:
		var angle = direction.signed_angle_to(lookDirection, Vector3.DOWN)
		
		var q = lerp(persone.rotation.y, persone.rotation.y + angle, 1)
		persone.rotation.y = q
		
		lookDirection = direction.normalized()
		
		persone.animation("walk")
		velocity.x = dir.x * SPEED
		velocity.z = dir.z * SPEED
	else:
		persone.animation("idle")
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()
	
func _input(event):
	if event is InputEventMouseMotion:
		cam_pointer.rotation.y -= event.relative.x * .01
		cam_pointer.rotation.x -= event.relative.y * .01
		
		direction = direction.rotated(Vector3.DOWN, event.relative.x * .01)
