using UnityEngine;
using System.Collections;

public class CrabMovementScript : MonoBehaviour {
    public float moveAmount = 1.0F, closeEnough = 0.5F, speed = 0.1F;
    public KeyCode leftInput = KeyCode.A, rightInput = KeyCode.D;
    public float minTargetZ = -7, maxTargetZ = 7;
    private bool lerping = false;
    private Vector3 startPos;
    private Vector3 targetPos;

    void Update () {

	    if(Input.GetKey(leftInput))
        {
            LerpMove(false);
            return;
        }
        if (Input.GetKey(rightInput))
        {
            LerpMove(true);
            return;
        }
    }

    private void LerpMove(bool movingRight)
    {
        if (!lerping)
        {
            startPos = transform.position;
            targetPos = new Vector3(startPos.x, startPos.y, startPos.z + (movingRight ? moveAmount : -moveAmount));
        }

        transform.position = Vector3.Lerp(startPos, targetPos, speed * Time.deltaTime);

        float currentZPos = transform.position.z;
        if (currentZPos > targetPos.z - closeEnough)
        {
            lerping = false;
        }

        /*

        if(currentZPos < 0 && currentZPos < minTargetZ)
        {
            lerping = false;
            transform.position = new Vector3(transform.position.x, transform.position.y, minTargetZ);
            return;
        }

        if (currentZPos > 0 && currentZPos > maxTargetZ)
        {
            lerping = false;
            transform.position = new Vector3(transform.position.x, transform.position.y, maxTargetZ);
            return;
        }
        */
    }
}
