class_name GrunkBeast extends Node3D
## The nefarious grunkbeest!
##
## Procedural animation adapted from https://github.com/CBerry22/Godot-4.0-Procedural-Animation

@export var move_speed := 6.0
@export var turn_speed := 6.0
@export var ground_offset := -1.5

@export_category("Step Parameters")
@export var step_height := 1.2
@export var step_time := 0.1
@export var step_distance := 1.0
@export var step_target_offset := 10.0

@onready var target_fl: BeastIKTarget = $Armature/TargetFL
@onready var target_fr: BeastIKTarget = $Armature/TargetFR
@onready var target_bl: BeastIKTarget = $Armature/TargetBL
@onready var target_br: BeastIKTarget = $Armature/TargetBR


func _process(delta: float) -> void:
	# Reorient based on relative leg position
	var p1 := Plane(target_bl.global_position, target_fl.global_position, target_fr.global_position)
	var p2 := Plane(target_fr.global_position, target_br.global_position, target_bl.global_position)
	var normal := (p1.normal + p2.normal).normalized()
	var reoriented_basis := (
		Basis(normal.cross(basis.z), normal, basis.x.cross(normal)).orthonormalized()
	)
	basis = basis.slerp(reoriented_basis, move_speed * delta).orthonormalized()

	# Reposition body to hang between legs
	var centroid := (
		(target_fl.position + target_fr.position + target_bl.position + target_br.position) / 4.0
	)
	var target_pos := centroid + basis.y * ground_offset
	var distance := basis.tdoty(target_pos - position)
	position = position.lerp(position + basis.y * distance, move_speed * delta)

	# Movement
	var direction := Input.get_axis("ui_down", "ui_up")
	translate(Vector3(0, 0, direction) * move_speed * delta)

	var a_direction := Input.get_axis("ui_right", "ui_left")
	rotate_object_local(Vector3.UP, a_direction * turn_speed * delta)
