extends KinematicBody

var speed = 380
var direction = Vector3()
var gravity = -40.8
var velocity = Vector3()
var lastPos = Vector3()
var oldpos = Vector2()
var ang = 0.0
var oldang = 0.0
var anim = 0.0

const IGNORE_VALUE = 0.005;

func _ready():
	get_node("AnimationTreePlayer").set_active(true)

func _physics_process(delta):
	
	direction = Vector3(0,0,0)
	var cam_rot_y = get_node("../Camera").rotation.y
	
	if Input.is_action_pressed("move_fw"):
		direction.x -= sin(cam_rot_y)
		direction.z -= cos(cam_rot_y)
	if Input.is_action_pressed("move_bw"):
		direction.x += sin(cam_rot_y)
		direction.z += cos(cam_rot_y)
	if Input.is_action_pressed("move_r"):
		direction.x -= sin(cam_rot_y - PI/2)
		direction.z -= cos(cam_rot_y - PI/2)
	if Input.is_action_pressed("move_l"):
		direction.x -= sin(cam_rot_y + PI/2)
		direction.z -= cos(cam_rot_y + PI/2)
	
	direction = direction.normalized()
	direction = direction * speed * delta
	
	velocity.y += gravity * delta
	velocity.x = direction.x
	velocity.z = direction.z
	
	velocity = move_and_slide(velocity, Vector3(0,1,0))
	
	if is_on_floor() and Input.is_key_pressed(KEY_SPACE):
		velocity.y = 80
		
	if Input.is_key_pressed(KEY_R):
		get_tree().reload_current_scene()
	
	
	var t = transform
	var speed = Vector2(t.origin.x,t.origin.z).distance_to(Vector2(lastPos.x,lastPos.z))
	
	var rotTransform
	var thisRotation
	
	if (speed >= IGNORE_VALUE):
		rotTransform = t.looking_at(lastPos,Vector3(0,1,0))
		thisRotation = Quat(t.basis).slerp(rotTransform.basis, 0.1)
		transform = Transform(thisRotation,t.origin)
		
	lastPos = t.origin

	rotation.x = 0
	rotation.z = 0
	
	if (speed <= IGNORE_VALUE and anim >= 0.2):
		anim -= 0.2
	if (speed >= IGNORE_VALUE and anim <= 1.8):
		anim += 0.2
	
	if (is_on_floor()):
		get_node("AnimationTreePlayer").blend2_node_set_amount("idle-run", min(anim, 1))
	
	