extends CharacterBody3D
class_name Wolf

@export var speed: float = 7.0
var despawn_threshold = -10

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

var player: Player
var world

@export var weapon: Weapon

@export var attack_distace: float = 1.3
@export var anim: AnimationPlayer

@export var drop: PackedScene
@export var drop_chance: float = 0.5

func _ready():
	player = get_tree().get_nodes_in_group("Player").back()
	world = get_tree().get_nodes_in_group("MainScene").back()


func _physics_process(delta):

	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta
	
	if player:
		look_at(player.position, Vector3.UP)
		rotation.x = 0.0
		rotation.z = 0.0
	
	#if position.distance_to(player.position) <= attack_distace:
	#	if anim.current_animation != "Attack":
	#		anim.speed_scale = 2.0
	#		anim.play("Attack")
		
	var angle: float = rotation.y
	var direction: Vector3 = Vector3.FORWARD
	direction = direction.rotated(Vector3.UP, angle).normalized()
	if direction:
		velocity.x = direction.x * speed
		velocity.z = direction.z * speed
	else:
		velocity.x = move_toward(velocity.x, 0, speed)
		velocity.z = move_toward(velocity.z, 0, speed)
	
	#if anim.current_animation != "Attack":
	#	if velocity.length() > 0.01:
	#		anim.speed_scale = 1.0
	#		anim.play("running")
	#	else:
	#		anim.speed_scale = 1.0
	#		anim.play("idle")
	move_and_slide()



func _on_health_death():
	queue_free()
