using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

	[SerializeField] Animator _animator;
	float _moveSpeed;
	[SerializeField] float _moveSpeedMax = 6;
	[SerializeField] float _moveSpeedSmooth = 3;
	Vector3 _movement;

	[SerializeField] float _rotateSmooth = 6f;
	[SerializeField] float _runSmooth = .5f;

	[SerializeField] float prevMoveAmount;

	float _leanAmount;

	// Update is called once per frame
	void Update () {
		Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
		Vector3 targetDirection = new Vector3(input.x, 0, input.y).normalized;

		_movement = Vector3.Lerp(_movement, targetDirection * _moveSpeedMax, _moveSpeedSmooth * Time.deltaTime);

		float moveAmount = _movement.magnitude / _moveSpeedMax;
		//float leanAmount = _animator.GetFloat("fLeanAmount");
		_leanAmount = Mathf.Lerp(_leanAmount, Mathf.Clamp(((prevMoveAmount - moveAmount) * 25), -1, 1), 10 * Time.deltaTime);
		_animator.SetFloat("fLeanAmount", _leanAmount);

		prevMoveAmount = moveAmount;

		_animator.SetFloat("fMoveAmount", moveAmount);
		transform.position += _movement * Time.deltaTime;

		float runAmount = _animator.GetFloat("fRunAmount");
		if(moveAmount > .9f) runAmount = Mathf.Lerp(runAmount, 1, _runSmooth * Time.deltaTime);
		else runAmount = Mathf.Lerp(runAmount, 0, _runSmooth * Time.deltaTime);
		_animator.SetFloat("fRunAmount", runAmount);

		if(targetDirection.magnitude < .001f) targetDirection = transform.forward;
		var targetRotation = Quaternion.LookRotation(targetDirection);
		transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, _rotateSmooth = 6f * Time.deltaTime);




	}
}
