using UnityEngine;
using ScrambleKit.Move;

public class MoveController : MonoBehaviour 
{
    public Vector2 MoveDir;

    public float MoveAcceleration = 40;
    public float StopDeceleration = 50;
    public float SpeedLimit = 6;

    private Rigidbody2D rb;
    private Vector3 origScale;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        origScale = transform.localScale;
    }

    public void FixedUpdate()
    {
        if (Exit.ExitClosed)
        {
            Stop();
            return;
        }

        if (MoveDir != Vector2.zero)
            Move();
        else
            Stop();
    }

    private void Move()
    {
        rb.AccelTowardVelocityByAtMost(SpeedLimit * MoveDir, MoveAcceleration);
        UpdateFacing();
    }

    private void Stop()
    {
        rb.AccelTowardVelocityByAtMost(Vector2.zero, StopDeceleration);
    }

    private void UpdateFacing()
    {
        if (MoveDir.x == 0)
            return;

        int facing = MoveDir.x < 0 ? -1 : 1;
        transform.localScale = new Vector3(origScale.x * facing, origScale.y, origScale.z);
    }

}
