Improving enemy AI
In the previous chapter, we learned how to create enemies that will chase the player if too close with it. However, the enemies look very stiff because they don't move at all when the player is not within its sight. Therefore, we will adjust the AI script a little bit to make the enemies able to patrol around the level randomly if the player is not detected.
First of all, open up the EnemyAI
script and add these variables on top:
Vector3 randomPos; float pauseInterval = 0; float pauseTime = 0;
The randomPos
variable is where the enemy will be moving to during patrolling. The randomPos
variable will be recalculated if the enemy has reached that position. The enemy will stand still for a while before moving to the next random position.
Next, add CalculateRandomPosition()
to the Start()
function:
void Start () { // Find player player = GameObject.FindWithTag ("Player"); CalculateRandomPosition (); }
This is how the CalculateRandomPosition()
function looks:
void CalculateRandomPosition...