extends CharacterBody3D

@export var speed = 2
@export var fall_acceleration = 75

var target_velocity = Vector3.ZERO

func _ready() -> void:
	position = Global.spawn_point
	%Camp.position = Global.spawn_point

func _physics_process(delta):
	RenderingServer.global_shader_parameter_set("player_position", position)

	%TileGround.update_chunks(position)

	# We create a local variable to store the input direction.
	var direction = Vector3.ZERO

	# We check for each move input and update the direction accordingly.
	if Input.is_action_pressed("move_right"):
		direction.x += 1
	if Input.is_action_pressed("move_left"):
		direction.x -= 1
	if Input.is_action_pressed("move_back"):
		# Notice how we are working with the vector's x and z axes.
		# In 3D, the XZ plane is the ground plane.
		direction.z += 1
	if Input.is_action_pressed("move_forward"):
		direction.z -= 1

	if direction != Vector3.ZERO:
		direction = direction.normalized()
		# Setting the basis property will affect the rotation of the node.
		$Pivot.basis = Basis.looking_at(-direction)

	# Ground Velocity
	target_velocity.x = direction.x * speed
	target_velocity.z = direction.z * speed

	# Vertical Velocity
	if not is_on_floor(): # If in the air, fall towards the floor. Literally gravity
		target_velocity.y = target_velocity.y - (fall_acceleration * delta)

	# Moving the Character
	velocity = target_velocity

	if direction != Vector3.ZERO:
		%PlayerAnimationPlayer.play('basic-movement/walk')
	else:
		%PlayerAnimationPlayer.play('basic-movement/idle')

	move_and_slide()
