Hello everyone, i’d like to add a wander function for my AI.
I instantiate a transform where they move to then it gets deleted and a new one is created, it repeats this as long as it is within viewable range but out of the player’s range.
It works but the problem is that before they move towards the new location they do a couple spins, probably because of the Rotate line in Move()
Relevant parts of the script:
public class VirusAI : MonoBehaviour {
void Awake()
{
target = player.transform;
myTransform = transform;
int x = Random.Range(-50, 50);
int z = Random.Range(-50, 50);
savedLoc = Instantiate(StartLoc, transform.position + new Vector3(x, 0.0f, z), transform.rotation);
}
#region Movement & Anim
void Update()
{
distance = Vector3.Distance(myTransform.position, target.position); // Check & store distance
if(distance > range * 4) return; //Stop if not viewable -> performance
if(distance < range * 2 && distance > range) // Out of range but viewable -> Wander
{
if (Vector3.Distance(transform.position, savedLoc.transform.position) < stop)
{
StartCoroutine(NewTarget()); //Create new random position
} else {
Move(savedLoc.transform); //Wander to next position
}
}
if (distance <= range)
{
Move(target); //Move to target(Player)
}
}
void Move(Transform target)
{
//Rotate to player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
//Move Forward
if (distance > stop) //Don't get too close
{
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
IEnumerator NewTarget()
{
yield return new WaitForSeconds(0.5f);
int x = Random.Range(-50, 50);
int z = Random.Range(-50, 50);
Destroy(savedLoc); //Remove old and create new location to "wander" to
savedLoc = Instantiate(StartLoc, transform.position + new Vector3(x, 0.0f, z), transform.rotation);
}
#endregion
}