using UnityEngine; using System.Collections; [RequireComponent(typeof(Rigidbody2D))] public class MissileController : MonoBehaviour { public float speed = 1; public float initVelocity = 5; public float boostCoolDown = 0.3f; public float difficulty = 0.0f; public int totalBoosts = 2; public ParticleSystem boostEffect; public GameObject Explosion; [HideInInspector] public Vector3 startVelocity; [HideInInspector] public Vector3 targetPos; [HideInInspector] public GameObject target; [HideInInspector] public Rigidbody2D targetRigid; [HideInInspector] public Collider2D[] ignoreList; [HideInInspector] public InteractableObject spawningObject; private Rigidbody2D rigid; private float startTime = 0.0f; private int reCalibrate = 0; // Use this for initialization void Start () { DontDestroyOnLoad(gameObject); startTime = Time.time; Collider2D thisCollider = GetComponent(); if (thisCollider != null) { foreach (Collider2D collider in ignoreList) { Physics2D.IgnoreCollision(thisCollider, collider); } } rigid = GetComponent(); rigid.velocity = startVelocity * initVelocity; Destroy(gameObject, boostCoolDown * totalBoosts + 1); } // Update is called once per frame void FixedUpdate () { if (Time.time - startTime >= boostCoolDown && reCalibrate < totalBoosts) { if (reCalibrate == 0) { if (target != null) { targetPos = target.transform.position; } } if (target != null) { moveTorwards(target); } reCalibrate++; startTime = Time.time; } } private void moveTorwards(Vector3 pos) { if (boostEffect != null) { boostEffect.startRotation = transform.rotation.eulerAngles.z * Mathf.Deg2Rad; boostEffect.Play(); } Vector2 direction = (pos - transform.position).normalized; Debug.DrawLine(transform.position, pos, Color.green,0.3f); rigid.velocity = direction * speed; //rigid.AddForce(direction * speed, ForceMode2D.Impulse); } private void moveTorwards(GameObject target) { if (target == null) return; if (targetRigid != null && reCalibrate == 1) { Debug.DrawLine(targetPos, target.transform.position, Color.blue, 0.3f); Vector2 pos = Vector3.Lerp( targetPos,target.transform.position,difficulty); moveTorwards(pos); return; } moveTorwards(target.transform.position); } void OnCollisionEnter2D(Collision2D coll) { InteractableObject colScript = coll.gameObject.GetComponent(); if (colScript == null || colScript == spawningObject ) { // Debug.Log("I ignored " + coll.gameObject.name); return; } //Debug.Log("I hit " + coll.gameObject.name); colScript.shot(); if (Explosion != null) { GameObject explosion = (GameObject)Instantiate(Explosion, transform.position, transform.rotation); Destroy(explosion, 2.0f); } Destroy(this.gameObject); } }