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

public class KeuhkMonsterScript : MonoBehaviour
{

    GameObject player;
    Vector3 offsetfly;

    public float speed;

    // Use this for initialization
    void Start()
    {
        player = GameObject.Find("player");
    }

    // Update is called once per frame
    void Update()
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.identity, 0.1f);

        float sped = speed;
        Vector3 offset;
        offsetfly += Random.insideUnitSphere * 0.1f;
        if (offsetfly.magnitude > 3) offsetfly = offsetfly.normalized * 3;
        if (Vector3.Distance(transform.position, player.transform.position) < 40)
        {

            offset = player.transform.position - transform.position;
            RaycastHit2D rh2d = Physics2D.Raycast(transform.position, offset.normalized, 150, ~(LayerMask.GetMask("enemy") | LayerMask.GetMask("wall") | (2 << Physics.IgnoreRaycastLayer)));
            bool fliercondition = rh2d.rigidbody == player.GetComponent<Rigidbody2D>() && Vector3.Distance(transform.position, player.transform.position) > 10;
            bool looksatme = Vector2.Dot(player.transform.up, -offset.normalized) > 0.6f;
            if (fliercondition && !looksatme)
            {
                offset += offsetfly;
                GetComponent<Animator>().SetBool("Attacking", true);
            }else
            {
                GetComponent<Animator>().SetBool("Attacking", false);
            }
            if (looksatme)
            {
                offset = -offset + Random.onUnitSphere;
                if (Vector2.Dot(GetComponent<Rigidbody2D>().velocity, offset) > 0)
                    sped = sped * 3;
                GetComponent<Animator>().SetBool("Cowering", true);
            }
            else
            {
                GetComponent<Animator>().SetBool("Cowering", false);
            }
            if (rh2d.rigidbody != player.GetComponent<Rigidbody2D>())
            {
                offset = Random.onUnitSphere;
                
            }
            //print(player.GetComponent<Rigidbody2D>());
            //print(rh2d.rigidbody);
        }
        else
        {
            offset = Random.onUnitSphere;
        }
        GetComponent<Rigidbody2D>().AddForce(offset.normalized * sped);

        transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.identity, 0.01f);
    }
}
