BGJ-2022.1/Assets/Scripts/AI/BasicPatrollingEnemyAI.cs

64 lines
2.5 KiB
C#
Raw Normal View History

using Movement;
2022-02-22 00:04:15 +03:00
using Pausable;
using UnityEngine;
namespace AI
{
2022-02-22 00:04:15 +03:00
public class BasicPatrollingEnemyAI : MonoBehaviour, IPausable
{
2022-02-25 12:45:02 +03:00
[SerializeField] protected bool isMovingRightInitially = false;
protected bool isMovingRight = false;
protected IMovement movement = null;
2022-02-25 12:45:02 +03:00
protected SpriteRenderer spriteRenderer = null;
2022-02-21 19:09:59 +03:00
protected CollisionChecker leftWallChecker = null;
protected CollisionChecker rightWallChecker = null;
protected CollisionChecker leftGroundChecker = null;
protected CollisionChecker rightGroundChecker = null;
2022-02-22 00:04:15 +03:00
#region IPausable
public bool IsPaused { get; protected set; } = false;
public virtual void Pause() => IsPaused = true;
public virtual void Resume() => IsPaused = false;
#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
2022-02-21 18:47:01 +03:00
protected bool ShouldChangeDirection
=> (isMovingRight && (rightWallChecker.IsCollided || !rightGroundChecker.IsCollided)) ||
(!isMovingRight && (leftWallChecker.IsCollided || !leftGroundChecker.IsCollided));
protected virtual void Awake()
{
movement = gameObject.AddComponent<EnemyMovement>();
2022-02-25 12:45:02 +03:00
spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
2022-02-21 19:09:59 +03:00
leftWallChecker = GetCollisionCheckerOnChild("Collision Checkers/Left Wall");
rightWallChecker = GetCollisionCheckerOnChild("Collision Checkers/Right Wall");
leftGroundChecker = GetCollisionCheckerOnChild("Collision Checkers/Left Ground");
rightGroundChecker = GetCollisionCheckerOnChild("Collision Checkers/Right Ground");
2022-02-25 12:45:02 +03:00
isMovingRight = isMovingRightInitially;
spriteRenderer.flipX = !isMovingRightInitially;
}
protected virtual void FixedUpdate()
{
2022-02-22 00:04:15 +03:00
if (IsPaused)
return;
if (ShouldChangeDirection)
2022-02-25 12:45:02 +03:00
{
isMovingRight = !isMovingRight;
2022-02-25 12:45:02 +03:00
spriteRenderer.flipX = !isMovingRight;
}
movement.Move(isMovingRight ? 1f : -1f);
}
2022-02-21 19:09:59 +03:00
protected CollisionChecker GetCollisionCheckerOnChild(string childName)
=> transform.Find(childName).GetComponent<CollisionChecker>();
}
}