extends Node

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

@onready var player: CharacterBody3D = get_parent()

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

  if Input.is_action_just_pressed("ui_accept") and player.is_on_floor():
    player.velocity.y = PlayerData.jump_velocity

  var input_dir := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
  var camera_pivot := player.get_node("CameraPivot") as Node3D
  var forward := -camera_pivot.global_transform.basis.z
  forward.y = 0
  forward = forward.normalized()
  var right := camera_pivot.global_transform.basis.x
  right.y = 0
  right = right.normalized()

  var direction := (forward * -input_dir.y + right * input_dir.x).normalized()

  if direction:
    player.velocity.x = direction.x * PlayerData.speed
    player.velocity.z = direction.z * PlayerData.speed
  else:
    player.velocity.x = move_toward(player.velocity.x, 0, PlayerData.speed)
    player.velocity.z = move_toward(player.velocity.z, 0, PlayerData.speed)

  player.move_and_slide()
