Unity Dev: Enemies, Beware!
Any game worth its salt has some sort of problem that you, as the player, need to overcome. In this case, we’re putting together a little side scroller space shooter. Logically, the best enemy for this scenario is laser shooting pterodactyls. Unfortunately, I don’t have a handy stash of assets to accomplish that so we’ll just say that our enemies are an unending stream of incredibly rude aliens with cool space ships.
Basic Enemy Setup
Your new companion, the Enemy Cube
Create a new, slightly smaller Cube in your Scene called “Enemy”, give it a swanky and unique material, then dump it in your Prefabs folder so that we can spawn them en masse later on. For now, we just want to get this one moving around.
We’re going to set up a script for our enemies as well to control their behaviour. Create a C# script in your Scripts folder and call it “Enemy”. Attach this to your Enemy
All we want to do here is take the Enemy object that we left in our scene and move it to the left. Once it’s off screen, we want to place it on the right side of the viewable area at a random vertical placement and have them move to the left again… forever. Or at least until we get the lasers set up to do some damage.
Much like our Player, we’ll create a void CalculateMovement()
function which will handle all the movement of our good friend, the enemy cube.
In this script, we tell it to move using the Translate()
method, multiplying our _speed
and Time.deltaTime
with the Vector3.left
short hand.
The far left side of our screen is at -11f
or so. We check for that and then ‘port our enemy cube back over to the right at 11f
and use Random.Range
to teleport it to a random point on the y-axis somewhere in between -4f
and 6f
Call CalculateMovement()
inside of our Update()
void and set up a _speed
variable for your enemy script. Don’t forget to add a [SerializeField]
to it so that you can muck around with their speed on the fly.
If we run our game, we can now watch our little green friend move across our screen forever. Fun!