Making the AI move randomly around the player's last known location
I've created an AI that uses a state machine by following a tutorial on Unity's YouTube channel and there's a section I wish to change to give it a more authentic feel. Here you can see how the AI moves around. Firstly, it's in a wander state where it goes to waypoints back and fourth and eventually when it spots the player, it will chase them. Now when the player breaks line of sight, the current code makes the AI stand on the spot and rotate for a few seconds to try and find the player and if not, it'll go back to wandering and if it does, it'll chase them all over again.
However, I feel like it'd look more real and authentic if the AI randomly moved around the area the player was last seen in. The AI already walks to the last known location already, it's just setting up a circular radius and then allowing them to walk around in it, but I'm not quite sure how to do that.
private void Search()
{
searchTimer += Time.deltaTime;
followTimer += Time.deltaTime;
if (followTimer >= enemy.followingDuration)
{
enemy.navMeshAgent.destination = enemy.chaseTarget.position;
enemy.navMeshAgent.Stop();
}
enemy.transform.Rotate(0, enemy.searchingTurnSpeed * Time.deltaTime, 0); //Rotates the enemy on the Y axis
enemy.meshRendererFlag.material.color = Color.white;
if (searchTimer >= enemy.searchingDuration)
{
InPatrolState(); //After a few seconds of searching, the enemy will stop rotating and will go back to patrolling
}
}
This here is the function used for when the AI searches for the player and I want to be able to amend it to do what I wish to do with it. If anyone could help me out, I'd extremely appreciate it, thanks. :)
Answer by OutOfRam · Oct 29, 2016 at 05:05 PM
Hi there,
I would personally start by setting a variable for wander radius, then use that and set a random position within that radius over and over again. try the following;
IEnumerator Search() {
while(true) { // This loops the behaviour untill you teminate manually
for (float i = 1; i < 10; 1 += 1) { //will loop 10 times, set it to the number of waypoints you want
searchPos[i] = Random.insideUnitCircle * searchRadius; //gives you coordinates at random
}
//SET NAVE MESH AGENT DESTINATION TO SEARCHPOS[variable]
//WHEN HE GETS THERE INCREASE variable AND DO IT AGAIN
if (vaiable is > searchPos.length)
{
//Run the patrol behaviour again
break;
}
else if (Player is found)
{
//Run follow behaviour
break;
}
yield return new WaitForSeconds(.5f)
}
I can't do all the work for you, so you'll need to fill in some areas on your own. If you still need help or if i made a mistake somewhere(this was all freehand, it happens) leave a comment and I'll try to help some more.
Your answer
Follow this Question
Related Questions
Ai sprite animation 8 directional movement 0 Answers
NPC move and find 0 Answers
Disable a Function when another and active (javascript AI) 1 Answer