using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy_Wander_Script : MonoBehaviour { public int speed = 4; public bool doesIdle = true; public bool doesFall = false; public float wakeDistance = 15; public int enemyLayer = 9; private float moveX; private float width; private float height; private int idleTime = 0; private void Start() { SpriteRenderer sprite = GetComponent(); width = GetComponent().bounds.size.x; height = GetComponent().bounds.size.y; Vector2 localScale = gameObject.transform.localScale; moveX = localScale.x < 0 ? -1 : 1; } void Update() { if (Static_GlobalStats.paused) { GetComponent().SetFloat("speed", 0); return; } if (gameObject.transform.position.y < -100) { Destroy(gameObject); return; } if (gameObject.GetComponent().enabled && Vector2.Distance(gameObject.transform.position, GameObject.FindWithTag("Player").transform.position) < wakeDistance) { Rigidbody2D rigidbody = gameObject.GetComponent(); if (doesIdle && Random.Range(0, 1000) <= 1) idleTime = Random.Range(20, 300); if (idleTime > 0) { idleTime--; } else { rigidbody.velocity = new Vector2(moveX * speed, rigidbody.velocity.y); } GetComponent().SetFloat("speed", Mathf.Abs(rigidbody.velocity.x)); GetComponent().SetBool("grounded", true); int layerMask = ~(1 << enemyLayer); for (float y = gameObject.transform.position.y - height * 0.55f; y <= gameObject.transform.position.y + height * 0.55f; y += 0.1f) { RaycastHit2D frontalHit = Physics2D.Raycast(new Vector2(gameObject.transform.position.x, y), new Vector2(moveX, 0), width * 0.55f, layerMask); if (frontalHit.collider && frontalHit.collider.tag != "Collectable" && frontalHit.collider.tag != "Projectile" && frontalHit.collider.tag != "Player") { flipEnemy(); break; } } if (!doesFall) { RaycastHit2D groundHit = Physics2D.Raycast(new Vector2(gameObject.transform.position.x + moveX * width * 0.55f, gameObject.transform.position.y), Vector2.down, 2 * height, layerMask); if (!groundHit.collider) { flipEnemy(); } } } } void flipEnemy() { moveX = -moveX; Vector2 localScale = gameObject.transform.localScale; localScale.x *= -1; transform.localScale = localScale; } }