Just as, for the player controller, we don't have the bullet prefab yet, but we do have a variable where the bullet prefab will be stored. This is great, but so far our code makes the enemy shoot at the same time as the player; instead, we would like the enemy to be autonomous. In order to achieve this, we need to change the code. The simplest implementation is that the enemy shoots a bullet after a random amount of time, for instance varying from one to three seconds. These two values are stored in the minShootingTime and maxShootingTime variables.
Thus, let's remove the check of the input of the player, but keep the check on the reload time. Then, inside the if statements, we need to also reset the reload time to a random value between minShootingTime and maxShootingTime. We can do this with a built-in class of Unity called Random, which does exactly this with the Range() function. As a result, the enemy will shoot every time the reload time has expired, and the reload time changes every time it shoots. The code now looks like the following:
void FixedUpdate() { // [...] // Fire as soon as the reload time is expired if(Time.time - lastTimeShot > reloadTime) { //Set the current time as the last time the spaceship has fired lastTimeShot = Time.time; //Set a random reload time reloadTime = Random.Range(minShootingTime, maxShootingTime); //Create the bullet Instantiate(bulletPrefab, transform.position, Quaternion.identity); } }
And with this said, congratulations. You have now finished implementing the enemy controller, at least for this chapter; in the next one, we will change it slightly.