Enemy_Wander_Script.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Enemy_Wander_Script : MonoBehaviour
  5. {
  6. public int speed = 4;
  7. public bool doesIdle = true;
  8. public bool doesFall = false;
  9. public float wakeDistance = 15;
  10. public int enemyLayer = 9;
  11. private float moveX;
  12. private float width;
  13. private float height;
  14. private int idleTime = 0;
  15. private void Start()
  16. {
  17. SpriteRenderer sprite = GetComponent<SpriteRenderer>();
  18. width = GetComponent<SpriteRenderer>().bounds.size.x;
  19. height = GetComponent<SpriteRenderer>().bounds.size.y;
  20. Vector2 localScale = gameObject.transform.localScale;
  21. moveX = localScale.x < 0 ? -1 : 1;
  22. }
  23. void Update()
  24. {
  25. if (Static_GlobalStats.paused) {
  26. GetComponent<Animator>().SetFloat("speed", 0);
  27. return;
  28. }
  29. if (gameObject.transform.position.y < -100)
  30. {
  31. Destroy(gameObject);
  32. return;
  33. }
  34. if (gameObject.GetComponent<Collider2D>().enabled && Vector2.Distance(gameObject.transform.position, GameObject.FindWithTag("Player").transform.position) < wakeDistance)
  35. {
  36. Rigidbody2D rigidbody = gameObject.GetComponent<Rigidbody2D>();
  37. if (doesIdle && Random.Range(0, 1000) <= 1) idleTime = Random.Range(20, 300);
  38. if (idleTime > 0)
  39. {
  40. idleTime--;
  41. }
  42. else
  43. {
  44. rigidbody.velocity = new Vector2(moveX * speed, rigidbody.velocity.y);
  45. }
  46. GetComponent<Animator>().SetFloat("speed", Mathf.Abs(rigidbody.velocity.x));
  47. GetComponent<Animator>().SetBool("grounded", true);
  48. int layerMask = ~(1 << enemyLayer);
  49. for (float y = gameObject.transform.position.y - height * 0.55f; y <= gameObject.transform.position.y + height * 0.55f; y += 0.1f)
  50. {
  51. RaycastHit2D frontalHit = Physics2D.Raycast(new Vector2(gameObject.transform.position.x, y), new Vector2(moveX, 0), width * 0.55f, layerMask);
  52. if (frontalHit.collider && frontalHit.collider.tag != "Collectable" && frontalHit.collider.tag != "Projectile" && frontalHit.collider.tag != "Player")
  53. {
  54. flipEnemy();
  55. break;
  56. }
  57. }
  58. if (!doesFall)
  59. {
  60. RaycastHit2D groundHit = Physics2D.Raycast(new Vector2(gameObject.transform.position.x + moveX * width * 0.55f, gameObject.transform.position.y), Vector2.down, 2 * height, layerMask);
  61. if (!groundHit.collider)
  62. {
  63. flipEnemy();
  64. }
  65. }
  66. }
  67. }
  68. void flipEnemy()
  69. {
  70. moveX = -moveX;
  71. Vector2 localScale = gameObject.transform.localScale;
  72. localScale.x *= -1;
  73. transform.localScale = localScale;
  74. }
  75. }