using UnityEngine;
using System.Collections;

public class EnemyFood : MonoBehaviour {


    Vector3 home;

    Vector3 velocity = Vector3.zero;

    Transform player;

    Vector3 target = Vector3.zero;

    public float movespeed = 3.0f;

    private Animator anim;
    private CharacterController cc;
	// Use this for initialization
	void Start () {
        player = FindObjectOfType<PlayerStats>().transform;
        home = transform.position;
        cc = GetComponent<CharacterController>();
        anim = GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void Update () {

        Vector3 toPlayer =  transform.position - player.position ;

        

        if (toPlayer.magnitude < 8) {
            target = toPlayer;
        } else {
            moveHome();
        }

        if (velocity == Vector3.zero) {
            
        } else {
            
            
        }


        if (target != Vector3.zero) {
            target = new Vector3(target.x, 0, target.z);
            anim.SetFloat("speed", 1);
            float step = 3.0f * Time.deltaTime;
            Vector3 newDir = Vector3.RotateTowards(transform.forward, target, step, 0.0F);
            Debug.DrawRay(transform.position, newDir, Color.red);
            transform.rotation = Quaternion.LookRotation(newDir);

            cc.Move((transform.forward + Vector3.up * -8) * Time.deltaTime * movespeed);
        } else {
            cc.Move((Vector3.up * -8) * Time.deltaTime * movespeed);
            anim.SetFloat("speed", 0);
        }
	
	}

    private void moveHome() {
        Vector3 toHome = home - transform.position;
        if (toHome.magnitude > 1) {
            target = toHome;
        } else {
            target = Vector3.zero;
        }
    }
}
