- Home /
Monster AI patrol an idle
Hi there guys/girls! :) Thanks for reading this first of all, so I'm making a game with monsters (RPG) and what l would like to do is that the monster moves left and right (Patrol), and after waiting some random time it stands still (Idle). So in the start the monster 1)moves for like lets say 5 seconds, 2)then becomes Idle, and after Idling for lets say 3 seconds, 3)it moves again do this process again and again infinitly, the code I wrote down here just keeps changing the Idle and Patrol each 1 second, I don't know, l hope you could help me figure it out, Thanks! using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MonsterMove : MonoBehaviour { [SerializeField] private float MinPatrolTime, MaxPatrolTime, MinIdleTime, MaxIdleTime; [SerializeField] private bool ShouldBeIdle=false; public float MonsterMoveSpeed; public float Distance=2f; [SerializeField] private bool ShouldBePatroling = true; private bool MovingRight = true;
public Transform groundDetection;
private void Start()
{
}
private void Update()
{
}
void FixedUpdate()
{
if (ShouldBePatroling&&!ShouldBeIdle)
{
Move();
StartCoroutine(PatrolTime());
}
else if (ShouldBeIdle==true&&!ShouldBePatroling) { //Idle Anim
Debug.Log("Doing Idle Anim");
StartCoroutine(IdleTime());
}
}
void Move()
{
transform.Translate(Vector2.right * MonsterMoveSpeed * Time.deltaTime);
int layer_mask1 = LayerMask.GetMask("Ground");
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, Distance, layer_mask1);
if (groundInfo.collider == false)
{
if (MovingRight == true)
{
transform.eulerAngles = new Vector3(0, -180, 0);
MovingRight = false;
}
else
{
transform.eulerAngles = new Vector3(0, 0, 0);
MovingRight = true;
}
}
}
IEnumerator PatrolTime()
{
yield return new WaitForSeconds(Random.Range(MinPatrolTime, MaxPatrolTime));
ShouldBePatroling = false;
ShouldBeIdle = true;
}
IEnumerator IdleTime()
{
yield return new WaitForSeconds(Random.Range(MinIdleTime, MaxIdleTime));
ShouldBePatroling = true;
ShouldBeIdle = false;
}
}