Hi, I was trying to make a simple ai escape script what I was trying to make is an enemy that goes to some patrol points and when it gets close to the player it stops for a few seconds and it flees I have code but it doesn’t work properly there were some few bugs like it doesn’t flee properly its kinda laggy and the speed shifts
public float speed;
public Transform target;
public float minimumDistance;
public Transform[] patrolPoints;
public float waitTime;
public int currentPointIndex;
public bool once;
public bool GoToPatrolPoint;
public bool run;
public Animator anim;
void Update()
{
if (run)
{
GoToPatrolPoint = false;
}
StartCoroutine(GoandStop());
if (transform.position != patrolPoints[currentPointIndex].position && GoToPatrolPoint)
{
transform.position = Vector2.MoveTowards(transform.position, patrolPoints[currentPointIndex].position, speed * Time.deltaTime);
anim.SetBool("isMoving", true);
}
else
{
anim.SetBool("isMoving", false);
if (once == false)
{
StartCoroutine(Wait());
once = true;
}
}
}
IEnumerator GoandStop()
{
if (run)
{
speed = 0;
anim.SetBool("SawPlayer", true);
yield return new WaitForSeconds(.35f);
anim.SetBool("SawPlayer", false);
speed = .8f;
Vector3 dir = transform.position - target.position;
transform.Translate(dir * speed * Time.deltaTime);
yield return new WaitForSeconds(1f);
GoToPatrolPoint = true;
run = false;
}
else
{
speed = 3f;
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(waitTime);
if(currentPointIndex + 1 < patrolPoints.Length)
{
currentPointIndex++;
}
else
{
currentPointIndex = 0;
}
once = false;
}