TurtleActions.cs 1.74 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
using UnityEngine;
using System.Collections;

public class TurtleActions : MonoBehaviour {
	public int health = 3;
	public Vector2 p;
	public GameObject projectile = null;
	public int speed = 5;

	public float dist = 0;

	private bool canShoot = true;
	private float timer = 0f;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		dist = DistanceToPlayer ().magnitude;
		p = DirectionToPlayer ();

		if (health <= 0) {
			Destroy (gameObject);
		}

		if (DistanceToPlayer ().magnitude < 5 && canShoot == true) {
			GameObject clone = Instantiate (projectile, this.transform.position, Quaternion.identity) as GameObject;
			clone.GetComponent<TurtleProjectile> ().move = DirectionToPlayer ();
			clone.GetComponent<TurtleProjectile> ().speed = speed;
			canShoot = false;
		}

		if (canShoot == false) {
			timer += Time.deltaTime;
			if (timer >= 2) {
				canShoot = true;
				timer = 0;
			}
		}
	}

	void GetHit(int d){
		health -= d;
	}

	Vector2 DistanceToPlayer(){
		Vector2 distance = new Vector2 (0,0);

		Vector2 place = this.transform.position;
		GameObject p = GameObject.FindGameObjectWithTag ("Player");

		distance = (Vector2)p.transform.position - place;
		return distance;
	}

	Vector2 DirectionToPlayerRaw(){

		Vector2 dir = new Vector2 (0,0);
		Vector2 distance = DistanceToPlayer ();

		dir = distance / distance.magnitude;

		return dir;
	}

	Vector2 DirectionToPlayer(){
		Vector2 dirRaw = DirectionToPlayerRaw ();
		Vector2 dir = new Vector2 (0,0);

		if (dirRaw.x > 0.5)
			dir = new Vector2 (1, 0);
		else if (dirRaw.x < -0.5)
			dir = new Vector2 (-1, 0);
		else if (dirRaw.y > 0.5)
			dir = new Vector2 (0, 1);
		else if (dirRaw.y < -0.5)
			dir = new Vector2 (0, -1);

		return dir;
	}
}