Galaxy Shooter —Basic Enemy AI
Objective: Create an enemy that travels down the screen. If the enemy touches the player, the enemy gets destroyed and the player loses health. If the enemy reaches the bottom of the screen, respawn them at the top with a random x position.
The Setup
Right click and create a new 3D cube. Rename the cube to enemy. Next create a material for the enemy and assign to the enemy gameobject. Now turn the enemy into a prefab by dragging the object to the prefabs folder in the project view.
Next create a new C# script called enemy and drag the script to the enemy prefab. This allows not only the prefab to be updated but also enemies in the hierarchy.
The Code
Before we do any actual code it's important that we understand what needs to happen. The best way is to write pseudo code.
First let's create a speed variable called speed. We know we can use transform.Translate() to move down.
Now we need to figure out where the bottom of the screen is. In my project the area I want the enemy to respawn at -5.4 on the y position. We can use a simple if statement that checks if we reached that point.
The final thing we need to do is respawn the enemy and randomize the x position on the enemy. We can simply use transform.position(). I want the x position to be randomized from -8 to 8. We can use Random.Range(-8, 8) to change the x position. We also need to make sure that the y position is changed to 8. The z position can be zero.
Now let's start coding.
This is what it looks like
There's one more thing we need to do. I want the enemy to be destroyed when it gets hit by the laser or player. If it hits the player then the player loses a life. If the player loses all their lives, then the player is destroyed.
There is a method we can use called OnTriggerEnter. This method gets called when a gameobject collides with another. You will need colliders for this to work. Make sure the colliders are set to is trigger.
Also how do we know what objects hit what. We can assign tags to gameobjects. For example, we can create a tag called laser and player, to know which gameobject is which in code.
Now let's see how this looks in the actual script.
As you can see the enemy has different code based on the tag. You may also see that I'm able to access components that touched the enemy. I created a damage method in the player script. The enemy is able to call that method when it touches the player.
This is how it turned out
If you want to play this game click here Galaxy Shooter by JokingJester1 (itch.io)