extends CharacterBody3D

const SPEED = 1.0
const ACCEL = 4.5

@onready var nav: NavigationAgent3D = $NavigationAgent3D
@export var target: CharacterBody3D = null
var last_direction = Vector3.ZERO

func set_target(t: CharacterBody3D):
  target = t
  
func _physics_process(delta: float) -> void:
  if not target:
    return
  nav.set_target_position(target.global_position)
  var current_location = global_transform.origin
  var next_location = nav.get_next_path_position()
  var dist = next_location - current_location
  var new_velocity = dist.normalized() * SPEED
  
  if snapped(new_velocity.x, 1):
    last_direction = Vector3(-sign(new_velocity.x), 1, 1)
  var t: Material = $MeshInstance3D.material_override
  t.uv1_scale = last_direction

  if dist.length() > 0.5:
    velocity = new_velocity
    move_and_slide()
