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

public class Missile : MonoBehaviour 
{
	public float rocketTurnSpeed = 50.0f;
	public float rocketSpeed = 45f;
	public float randomOffset = 0.0f;

	private Transform target;

	// Use this for initialization
	void Start () 
	{
		target = GameObject.Find ("Player").GetComponent <Transform> ();
	}

	// Update is called once per frame
	void Update () 
	{
		if (target != null)
		{
			if ((target.position - transform.position).magnitude > 50)
			{
				randomOffset = 100.0f;
				rocketTurnSpeed = 90.0f;
			}
			else
			{
				randomOffset = 5f;
				//if close to target
				if ((target.position - transform.position).magnitude < 10)
				{
					rocketTurnSpeed = 180.0f;
				}
			}

			Vector3 direction = target.position - transform.position + Random.insideUnitSphere * randomOffset;
			direction.Normalize();
			transform.rotation = Quaternion.RotateTowards (transform.rotation, Quaternion.LookRotation(direction), rocketTurnSpeed * Time.deltaTime);
			transform.Translate (Vector3.forward * rocketSpeed * Time.deltaTime);
		}

		transform.eulerAngles =  new Vector3 (0, transform.eulerAngles.y, 0);
	}

	void OnTriggerEnter (Collider other)
	{
		Destroy (this.gameObject);
	}
}
