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

public class EnemyFlyTowardScript : 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 () {
        Vector3 offset;
        offsetfly += Random.insideUnitSphere * 0.1f;
        if (offsetfly.magnitude > 3) offsetfly = offsetfly.normalized*3;
        if (player != null && Vector3.Distance(transform.position, player.transform.position) < 40)
        {
            
            offset = player.transform.position - transform.position;
            RaycastHit2D rh2d = Physics2D.Raycast(transform.position, offset.normalized, 40, ~(LayerMask.GetMask("enemy") | (2 << Physics.IgnoreRaycastLayer)));
            if (rh2d.rigidbody == player.GetComponent<Rigidbody2D>() && Vector3.Distance(transform.position, player.transform.position) > 10)
            {
                offset += offsetfly;
            }
            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 * speed);

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