My journey becoming a Unity game developer: Enemy prototype for Galaxy Invaders
Objective: Create an Enemy prefab with a behavior of moving downward at a certain speed within a certain range. Also, the Enemy will be able to go off the bottom of the screen, then reappear at a random position at the top of the screen.
To create an Enemy prototype in our game, simply create a 3D Cube with a Scale of 0.7 along the 3 axes. Create a Material name Enemy_mat, and change the Albedo color to red. Create a new C# script name EnemyBehavior, and attach it to the Enemy game object. Last thing is to drag the Enemy game object into the Prefabs folder to make it officially a prefab to create multiple enemies in the game.
At this time the Enemy can’t collide with the Laser and Player objects because none of these objects have Rigidbody components attached to them. This will be addressed at another time.
In the EnemyBehavior script, we will set the Enemy up to move downward. Create a new Private Type Float variable name _speed with a value of 4f to represent how many meters the enemies will move per second. Also, attach a SerializeField attribute with the _speed variable.
In the Update() function, we’re going to make the Enemy move downward at 4 meters per second by using the transform.Translate() method. Have it move Down on the Vector3, then multiply by speed and real-time.
Watch the Enemy move downward at 4 meters per second.
Next, we need to check for when the Enemy disappears at the bottom of the screen which was at -6 on the Y-axis for us. Then, check for when they disappear on each side of the screen which was -9 on the left, and 9 on the right.
Back in the EnemyBehavior script, 2 new SerializeField Private Float variables. One name _minX with a value of -9f, and the other name _maxX with a value of 9f. This will represent the minimum and maximum movement allowed on the X-axis for the Enemy object.
In the Update() function, check IF the Enemy’s position has moved below -6 on the Y-axis. If this condition is true, set the Enemy’s transform position to equal new Vector3 positions with the X position set to a Random Range of _minX and _maxX. Also, set the Y position to 8 which is the top of the screen, and zero on the Z position which we aren’t using.
The Enemy is now appearing from various positions on the X-axis at the top of the screen.
To make this code more readable and optimized, let’s create a new variable inside the IF statements with a Type Float name randomX. RandomX will have a value of Random Range with _minX and _maxX passed in. In the Enemy’s transform position we will remove the Random Range on the X-axis and pass in the randomX variable instead to still select random positions on the X-axis for the enemies as a new Vector3 X position.
Enemy still reappearing at different positions on the X-axis using the randomX variable.