Unity 2D Prototype part 4 – Basic AI

      Comments Off on Unity 2D Prototype part 4 – Basic AI

Our AI will be relatively simple. We already have it automatically moving down the screen so the only thing we really need to do is have the enemies spawn on their own.

To start with we’ll update EnemySpawner so that instead of using the right mouse click the enemies would spawn on their own time.

First we’ll comment out the code in the Update method so that clicking no longer triggers an enemy to spawn. We’ll add 3 new methods to the class. OnEnable and OnDisable are both MonoBehaviour methods that get called automatically when the component becomes enabled or disabled, which our navigation methods are doing for us. When the spawner is enabled we want to start spawning enemies every second. To do this we call InvokeRepeating which is another function on MonoBehaviour.

Given the method name, it will wait for the time to pass and call the method on an interval specified by repeatRate. Time and repeatRate are both in seconds, so in our case below when we call InvokeRepeating we wait for 1 second then start calling Spawn every 1 second after that.

In OnDisable we call CancelInvoke, which simply stops all scheduled invokes to the given method. This causes the InvokeRepeating we did in OnEnable to be cancelled.

In the spawn method itself we’ll do our GameObject.Instantiate as we were previously doing on the mouse click, however for the position we’ll be using a position 50 pixels away from the right side of the screen and above the screen to test with. Our last step will be to randomize the starting position.


Because we’re now spawning the enemy off screen we need to update the enemy movement script so that the destruction only happens if the enemy had been visible. To do this we’ll simply keep a private variable to track the visibility of the enemy in the previous frame. If the enemy has gone from visible to not visible then we know they were on the screen but went off the bottom.


 

After testing and confirming that the enemies are spawning and the being counted towards the score or health as expected we just need to update the spawner script so that the x position the enemy spawns at is randomized. To do this we’ll use the UnityEngine.Random class to get a random value inside the bounds of the screen. We’ll also add an offset of 32 since that’s the size of the enemy, to ensure that the enemy always shows completely within the bounds of the screen.

The enemies move a little slow though, so jack up the speed a bit.