59 lines
2.3 KiB
C#
59 lines
2.3 KiB
C#
|
using Movement;
|
||
|
using UnityEngine;
|
||
|
|
||
|
namespace AI
|
||
|
{
|
||
|
public class BasicPatrollingEnemyAI : MonoBehaviour
|
||
|
{
|
||
|
[SerializeField] protected bool isMovingRight = false;
|
||
|
|
||
|
[Space]
|
||
|
[Header("Left Detector")]
|
||
|
[SerializeField] protected Vector2 leftCliffDetectorOrigin = Vector2.left;
|
||
|
[SerializeField] protected Vector2 leftCliffDetectorSize = Vector2.one;
|
||
|
|
||
|
[Space]
|
||
|
[Header("Right Detector")]
|
||
|
[SerializeField] protected Vector2 rightCliffDetectorOrigin = Vector2.right;
|
||
|
[SerializeField] protected Vector2 rightCliffDetectorSize = Vector2.one;
|
||
|
|
||
|
[Space]
|
||
|
[Header("Right Detector")]
|
||
|
[SerializeField] protected LayerMask groundLayerMask = ~(1 << 6); // Everything except the "Player" layer
|
||
|
|
||
|
protected IMovement movement = null;
|
||
|
protected Collider2D[] nonAllocColliderArray = new Collider2D[10];
|
||
|
|
||
|
protected Vector2 leftCliffPosition => GetCliffPositionInWorld(leftCliffDetectorOrigin);
|
||
|
protected Vector2 rightCliffPosition => GetCliffPositionInWorld(rightCliffDetectorOrigin);
|
||
|
|
||
|
protected bool IsLeftDetectorCollided => Physics2D.OverlapBoxNonAlloc(leftCliffPosition, leftCliffDetectorSize, 0, nonAllocColliderArray, groundLayerMask) != 0;
|
||
|
protected bool IsRightDetectorCollided => Physics2D.OverlapBoxNonAlloc(rightCliffPosition, rightCliffDetectorSize, 0, nonAllocColliderArray, groundLayerMask) != 0;
|
||
|
|
||
|
protected virtual void Awake()
|
||
|
{
|
||
|
movement = gameObject.AddComponent<EnemyMovement>();
|
||
|
}
|
||
|
|
||
|
protected virtual void FixedUpdate()
|
||
|
{
|
||
|
if ((isMovingRight && !IsRightDetectorCollided) || (!isMovingRight && !IsLeftDetectorCollided))
|
||
|
isMovingRight = !isMovingRight;
|
||
|
|
||
|
movement.Move(isMovingRight ? 1f : -1f);
|
||
|
}
|
||
|
|
||
|
protected Vector2 GetCliffPositionInWorld(Vector2 cliffPosition)
|
||
|
=> cliffPosition + (Vector2)transform.position;
|
||
|
|
||
|
protected virtual void OnDrawGizmosSelected()
|
||
|
{
|
||
|
Gizmos.color = IsLeftDetectorCollided ? Color.green : Color.red;
|
||
|
Gizmos.DrawWireCube(leftCliffPosition, leftCliffDetectorSize);
|
||
|
|
||
|
Gizmos.color = IsRightDetectorCollided ? Color.green : Color.red;
|
||
|
Gizmos.DrawWireCube(rightCliffPosition, rightCliffDetectorSize);
|
||
|
}
|
||
|
}
|
||
|
}
|