My code is designed to make the enemy navigate between checkpoints which are manually assigned using the shortest path it can find. It works for the first 2 checkpoints but then gets ‘stuck’ at the second checkpoint. Can you see what my issue is?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enShort3 : MonoBehaviour {
//this code will find the closest checkpoint to the enemy and move them towards it repeatedly
public GameObject[] verts; //array of checkpoints for enemy to move between
Transform objective; //transform for where enemy is aiming to go
int shortex = 0; //index for checkpoint with shortest path
Transform spawn; //ransform for enemies initial spawn
float shortest = 0; //record of shortest path found
public float speed = 10f; //speed mutliplier for enemy movement
private void Start()
{
spawn = this.transform; //records location at spawn
shortest = Vector3.Distance(spawn.transform.position, verts[0].transform.position); //default quickest path is between enemy's spawn and first
//checkpoint index
shortex = 0; //index of first checkpoint
}
private void FixedUpdate()
{
objective = verts[shortex].transform; //enemy's objective is defined by the index of the shortest path found in the array
this.transform.position += transform.forward * Time.deltaTime * speed; //move the enemy forward constantly
this.transform.LookAt(objective); //Rotate the enemy towards the objective
if (Vector3.Distance(this.transform.position, objective.position) < 5) //if the enemy is close enough to its current objective...
{
for (int x = 0; x < verts.Length; x++) //for every array value...
{
if (x < verts.Length - 3) //if the current index is not 2 below the end of the array...
{
if (Vector3.Distance(verts[x].transform.position, verts[x + 1].transform.position) <
Vector3.Distance(verts[x].transform.position, verts[x + 2].transform.position)) //check if the distance to the second array index
//is shorter than the distance to the third one as the enemy is
//already at the first index
{
float temp = Vector3.Distance(verts[x].transform.position, verts[x + 1].transform.position); //record the shorter distance
if (temp <= shortest) //check if the shorter distance is shorter than the shortest found so far
{
shortest = temp; //if it is, update the shortest distance
shortex = x + 1; //set the index to point towards the shortest distance
}
}
else if (Vector3.Distance(verts[x].transform.position, verts[x + 1].transform.position) > //repeat the same here
Vector3.Distance(verts[x].transform.position, verts[x + 2].transform.position))
{
float temp = Vector3.Distance(spawn.transform.position, verts[x + 2].transform.position);
if (temp < shortest)
{
shortest = temp;
shortex = x + 2;
}
}
}
objective = verts[shortex].transform; //set the objective using the closest checkpoint found
}
}
}
}