using Movement; using Pausable; using UnityEngine; namespace AI { public class BasicPatrollingEnemyAI : MonoBehaviour, IPausable { [SerializeField] protected bool isMovingRightInitially = false; protected bool isMovingRight = false; protected IMovement movement = null; protected SpriteRenderer spriteRenderer = null; protected Animator animator = null; protected CollisionChecker leftWallChecker = null; protected CollisionChecker rightWallChecker = null; protected CollisionChecker leftGroundChecker = null; protected CollisionChecker rightGroundChecker = null; #region IPausable public bool IsPaused { get; protected set; } = false; public virtual void Pause() { IsPaused = true; animator.enabled = !IsPaused; } public virtual void Resume() { IsPaused = false; animator.enabled = !IsPaused; } #endregion // If moving Right, and either there's no more ground to move into or there is a wall at the Right side of the enemy OR // If moving Left, and either there's no more ground to move into or there is a wall at the Left side of the enemy // We should change directions protected bool ShouldChangeDirection => (isMovingRight && (rightWallChecker.IsCollided || !rightGroundChecker.IsCollided)) || (!isMovingRight && (leftWallChecker.IsCollided || !leftGroundChecker.IsCollided)); protected virtual void Awake() { movement = gameObject.AddComponent(); spriteRenderer = gameObject.GetComponent(); animator = gameObject.GetComponent(); leftWallChecker = GetCollisionCheckerOnChild("Collision Checkers/Left Wall"); rightWallChecker = GetCollisionCheckerOnChild("Collision Checkers/Right Wall"); leftGroundChecker = GetCollisionCheckerOnChild("Collision Checkers/Left Ground"); rightGroundChecker = GetCollisionCheckerOnChild("Collision Checkers/Right Ground"); isMovingRight = isMovingRightInitially; spriteRenderer.flipX = !isMovingRightInitially; } protected virtual void FixedUpdate() { if (IsPaused) return; if (ShouldChangeDirection) { isMovingRight = !isMovingRight; spriteRenderer.flipX = !isMovingRight; } movement.Move(isMovingRight ? 1f : -1f); } protected CollisionChecker GetCollisionCheckerOnChild(string childName) => transform.Find(childName).GetComponent(); } }