Setting up the Dark Side
A game isn’t very fun unless it has an enemy. Lets set up an enemy for our game.
First of all, we can create a 3D cube object to represent the enemy. Right click in the Hierarchy, select 3D Object, Cube. In the Inspector, lets rename the cube object to Enemy and reduce his size slightly less than the player object by changing the scale to 0.75 on the x, y and z axis.
Since we will be spawning enemies randomly, it is bes we make our enemy a prefab. To do this, drag the enemy object from the Hierarchy into the Prefab folder in the Assets section.
Let give our enemy a Material. In the Materials folder, right click and select Create, Material. Name it Enemy_mat. Change the color to red and finally drag the new material over the Enemy Prefab. It is important you drag it over the prefab and not the Enemy in the Hierarchy. This way the material will get applied to every instantiated enemy.
Now that the enemy is set on our board, we need to give it properties. We will create an Enemy script to do this.
Right click on the Script folder and select Create, C# Script. Name it Enemy and drag it over the Enemy prefab.
Now that we created a new enemy script and applied it to out enemy prefab, we can start to write our code.
Lets double click on the enemy script to open it up in our editor.
Lets say we want our enemy to spawn at the top of the screen and move downwards at a speed of 4 m/s.
We will have to create a variable for this speed.
Since it is in good practice to make most all of out variables private, if we add the [SerializeField] before the variable declaration, we will be able to see it in the Inspector.
If we want our enemy to be spawned off screen, we can set its Y coordinates when we start the script. So in void Start() we can add the following:
Now, we want our enemy to move downwards towards and beyond our player. We can do this with a transform.Translate. We do this in the Update function of the script that gets called 60 times per second.
Don’t forget that in order for the enemy to move at 4 m/s, we must use this in our script.
If we save and play what we have so far, we should see out player spawn above the screen and move downwards.
Here the enemy goes past the player and keeps moving down forever. What if we made the enemy re-spawn at the top once he has moved off screen. We can do this by using an if statement checking for the enemy’s position and if it goes beyond a certain point, we can send it back to the top.
This is nice and all, but how about we get the enemy to re-spawn at a random coordinate on the x axis.
For this we need to create random numbers within a certain range. This range is basically the width of our playing field.
We now have an enemy object that moves down towards the player and will re-spawn at the top in a random position on the x axis. See you in the next one.