using UnityEngine;
using System.Collections;

public class TopDownMovementController : MonoBehaviour {

    public float MaxSpeed=4f;
    public float Accel=51f;
    public float Friction=21f;

    public Vector2 MoveAim;

    private Vector2 speed;
    private Rigidbody2D r2;
    private Animator anim;

	void Start () {
        speed = Vector2.zero;
        r2 = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
	}
	
	void FixedUpdate () {
        AdjustSpeed();
        Move();
	}

    private void AdjustSpeed()
    {
        if(MoveAim.magnitude == 0)
        {
            // decrease speed by Friction, not less than zero
            float s = Mathf.Max(0, speed.magnitude - Friction * Time.fixedDeltaTime);
            speed = s * speed.normalized;
            if (s == 0)
                anim.SetBool("Walking", false);
        }
        else
        {
            // accel speed by Accel, not more than MaxSpeed
            speed += MoveAim.normalized * Accel * Time.fixedDeltaTime;
            float s = Mathf.Min(MaxSpeed, speed.magnitude);
            speed = s * speed.normalized;
            anim.SetBool("Walking", true);
        }
    }

    private void Move()
    {
        Vector2 accel = speed - r2.velocity;
        Vector2 force = r2.mass * accel / Time.fixedDeltaTime;
        r2.AddForce(force);
    }
}
