12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- 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<SpriteRenderer>();
- width = GetComponent<SpriteRenderer>().bounds.size.x;
- height = GetComponent<SpriteRenderer>().bounds.size.y;
- Vector2 localScale = gameObject.transform.localScale;
- moveX = localScale.x < 0 ? -1 : 1;
- }
- void Update()
- {
- if (Static_GlobalStats.paused) {
- GetComponent<Animator>().SetFloat("speed", 0);
- return;
- }
- if (gameObject.transform.position.y < -100)
- {
- Destroy(gameObject);
- return;
- }
- if (gameObject.GetComponent<Collider2D>().enabled && Vector2.Distance(gameObject.transform.position, GameObject.FindWithTag("Player").transform.position) < wakeDistance)
- {
- Rigidbody2D rigidbody = gameObject.GetComponent<Rigidbody2D>();
- 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<Animator>().SetFloat("speed", Mathf.Abs(rigidbody.velocity.x));
- GetComponent<Animator>().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;
- }
- }
|