using UnityEngine;
using System.Collections;

// This script is the fruit.  It is a projectile.
public class Projectile2 : MonoBehaviour
{
	public EnemyMovement enemy;

	public GameObject impactEffect;

	private Rigidbody2D myRigidBody2D;

	public float speed;

	public float rotationSpeed;

	private Transform target;

	public float damageToGive;

	// Use this for initialization
	void Start()
	{
		if (FindObjectOfType<EnemyMovement> () != null)
		{
			enemy = FindObjectOfType<EnemyMovement> ();

			myRigidBody2D = GetComponent<Rigidbody2D> ();

			target = enemy.transform;

			if (enemy.transform.position.x < transform.position.x)
			{
				rotationSpeed = -rotationSpeed;
			}
		}
	}

	// Update is called once per frame
	void Update ()
	{
		if (FindObjectOfType<EnemyMovement> () != null)
		{
			Vector3 angle = (target.position - transform.position).normalized;

			if (Time.timeScale != 0)
			{
				myRigidBody2D.AddForce (angle * speed);
				myRigidBody2D.angularVelocity = rotationSpeed;
			}
		}
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if (other.name == "Enemy" || other.name == "Floor" || other.name == "Roof" || other.name == "Left" || other.name == "Right" || other.name == "Lightning")
		{
			Instantiate(impactEffect, transform.position, transform.rotation);
			Destroy (gameObject);
			if (other.name == "Enemy")
			{
				other.GetComponent<EnemyHealth> ().giveDamage (damageToGive);
			}
		}
	}
}
