You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.7 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. [RequireComponent(typeof(Rigidbody2D))]
  4. public class MissileController : MonoBehaviour {
  5. public float speed = 1;
  6. public float initVelocity = 5;
  7. public float boostCoolDown = 0.3f;
  8. public float difficulty = 0.0f;
  9. [HideInInspector]
  10. public Vector3 startVelocity;
  11. [HideInInspector]
  12. public Vector3 targetPos;
  13. [HideInInspector]
  14. public GameObject target;
  15. [HideInInspector]
  16. public Rigidbody2D targetRigid;
  17. [HideInInspector]
  18. public Collider2D[] ignoreList;
  19. [HideInInspector]
  20. public InteractableObject spawningObject;
  21. private Rigidbody2D rigid;
  22. private float startTime = 0.0f;
  23. private int reCalibrate = 0;
  24. // Use this for initialization
  25. void Start () {
  26. startTime = Time.time;
  27. Collider2D thisCollider = GetComponent<Collider2D>();
  28. if (thisCollider != null) {
  29. foreach (Collider2D collider in ignoreList) {
  30. Physics2D.IgnoreCollision(thisCollider, collider);
  31. }
  32. }
  33. rigid = GetComponent<Rigidbody2D>();
  34. rigid.velocity = startVelocity * initVelocity;
  35. Destroy(gameObject, 1.5f);
  36. }
  37. // Update is called once per frame
  38. void FixedUpdate () {
  39. if (Time.time - startTime >= boostCoolDown && reCalibrate < 2) {
  40. if (reCalibrate == 0) {
  41. targetPos = target.transform.position;
  42. }
  43. if (target != null) {
  44. moveTorwards(target);
  45. } else {
  46. moveTorwards(targetPos);
  47. }
  48. reCalibrate++;
  49. startTime = Time.time;
  50. }
  51. }
  52. private void moveTorwards(Vector3 pos) {
  53. Vector2 direction = (pos - transform.position).normalized;
  54. Debug.DrawLine(transform.position, pos, Color.green,0.3f);
  55. rigid.velocity = direction * speed;
  56. //rigid.AddForce(direction * speed, ForceMode2D.Impulse);
  57. }
  58. private void moveTorwards(GameObject target) {
  59. if (targetRigid != null && reCalibrate == 1) {
  60. Debug.DrawLine(targetPos, target.transform.position, Color.blue, 0.3f);
  61. Vector2 pos = Vector3.Lerp( targetPos,target.transform.position,difficulty);
  62. moveTorwards(pos);
  63. return;
  64. }
  65. moveTorwards(target.transform.position);
  66. }
  67. void OnCollisionEnter2D(Collision2D coll) {
  68. InteractableObject colScript = coll.gameObject.GetComponent<InteractableObject>();
  69. if (colScript == null || colScript == spawningObject ) {
  70. Debug.Log("I ignored " + coll.gameObject.name);
  71. return;
  72. }
  73. Debug.Log("I hit " + coll.gameObject.name);
  74. colScript.shot();
  75. }
  76. }