Trying to get my AI to move either left or right for a random amount of time. I did this by using a bunch of bool’s to figure out other things. Just need some help because when I start it up, it doesn’t move at all right now, but before when I didn’t have all the boolean checks, it accelerated forever.
Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyAI : MonoBehaviour
{
public float Speed;
public float maxSpeed;
public bool goingLeft;
public bool patrolling;
public bool end;
public float patrolValues;
public float Health = 1f;
public Rigidbody2D rb;
public Animator anim;
private void Start()
{
goingLeft = true;
patrolValue();
patrolling = false;
}
//AI Health Mechanic
//everything under this point is the patrol stuff
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
patrolStart();
}
}
void patrolStart()
{
if (!patrolling && !end)
{
Patrol();
}
}
void patrolValue()
{
patrolValues = Random.Range(1f, 2f);
Patrol();
StartCoroutine(patrolLength());
}
void Patrol()
{
if (goingLeft)
{
if (!end)
{
rb.AddForce(transform.right * -Speed);
patrolling = true;
}
}
else
{
if (!end)
{
rb.AddForce(transform.right * Speed);
patrolling = true;
}
}
}
void TurnAround()
{
goingLeft = !goingLeft;
patrolling = false;
Patrol();
}
IEnumerator patrolLength()
{
yield return new WaitForSeconds(patrolValues * 10);
TurnAround();
end = true;
}
}