extends CharacterBody3D



const SPEED = 3.5
const RUN_MULT = 2.0
const JUMP_VELOCITY = 4.5
const LIN_ACCEL = 0.25
const ANG_ACCEL = 0.25
const INNERTIA = 0.4

var animp : AnimationPlayer
var anim_tree : AnimationTree

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
var speed = SPEED
func _ready():
	anim_tree = $Abe_Lo/AnimationTree
	animp = $Abe_Lo/AnimationPlayer
	animp.play("ANIM_Abe_Idle_01")	
	animp.speed_scale = 1.5

func map( value : float , in_min : float, in_max : float, out_min : float, out_max : float ):
	#=( ( value - in_min ) / ( in_max - in_min ) * ( out_max-out_min ) + out_min)
	var mapped_value = ( value - in_min ) / ( in_max - in_min ) * ( out_max-out_min ) + out_min
	return mapped_value
	
func update_tree():
	anim_tree["parameters/Walk/blend_amount"] = animp.speed_scale / 1.5
	anim_tree["parameters/Run/blend_amount"] = map ( speed , SPEED , SPEED * RUN_MULT , 0 , 1 )
	
	
func _physics_process(delta):
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta
	else:
		anim_tree["parameters/Jump/blend_amount"] = move_toward( anim_tree["parameters/Jump/blend_amount"] , 0.0 , 0.1)

	# Handle jump.
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		anim_tree["parameters/Jump/blend_amount"] = 1.0

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir = Input.get_vector("left", "right", "up", "down")
	var run = Input.is_action_pressed("run")
	
	if run:
		speed  = move_toward( speed , SPEED * RUN_MULT , LIN_ACCEL )
	else:
		speed  = move_toward( speed , SPEED , LIN_ACCEL )
	
	# Caculate directions from input	
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	var direction2d = Vector2(-direction.x,direction.z)
	
	#moving
	if direction and (is_on_floor() or (not is_on_floor() and is_on_wall()) ):
		animp.speed_scale = 1.5
		velocity.x = direction.x * speed
		velocity.z = direction.z * speed
		#if speed > SPEED:
			#$GPUParticles3D.amount_ratio = speed / ( SPEED * RUN_MULT )

		var new_rotation =  Vector3( 0.0, direction2d.angle() - (PI/2) , 0.0 )

		$Abe_Lo.rotation = Vector3( 0.0 , rotate_toward( $Abe_Lo.rotation.y , new_rotation.y , ANG_ACCEL ), 0.0)
	else:
		if is_on_floor():
			velocity.x = move_toward(velocity.x, 0, INNERTIA )
			velocity.z = move_toward(velocity.z, 0, INNERTIA )
			animp.speed_scale = move_toward( animp.speed_scale, 0 , .05 )
			
			
		$GPUParticles3D.amount_ratio = 0.0
	update_tree()
	move_and_slide()
