Made With Unity | 2D Space Shooter Part 4: The Enemy
In this series of article / tutorials we are going to be making a small 2D Space Shooter using Unity3D and later on using the New Input System.
Creating The Enemy
Add a new 3D Object on the Hierarchy window and this time it will be a Sphere, named it Enemy. Also create a new material and were going to call it enemy_mat, choose a color to represent your Enemy and attach the new created material to the Enemy GameObject
Create a new script on the Project windows named Enemy, add the new script component to the Enemy.
Take the Enemy GameObject and drag it in to the Prefabs folder on the Project window (notice that the Enemy object change to a light blue).
Before continuing to add some behavior to our Enemy we need to make a couple of changes.
Adding The Rigidbody Component
On our Prefabs folder to both Laser and Enemy object we are going to add a Rigidbody component and remove the check mark where it says Use Gravity
Activating Is Trigger On The Colliders
Still on the Prefabs folder, find the Colliders (Laser is the Capture Collider and the Enemy is the Sphere Collider), and check Is Trigger.
On either GameObjects go to the top where it says Tag, press it and select Add Tag… On this new windows press the + sing and add two new tags, Laser and Enemy.
Go back to the Prefabs folder and on each object give there designated tags. To the Enemy give is Tag as Enemy and the Laser will have a Tag of Laser. On the Hierarchy select the Player and tag it with the Player tag.
Double click the Enemy script and type the following:
Line 14 to 23 we are moving the player, a new float variable is created on line 20 to store a random value, for the X axis, that is going to be generated when the enemy is not destroyed and it will popup again on the top of the screen. A new method is showed on line 25, OnTriggerEnter() that will be called as soon the Enemy is being touch by other object, this is the reason we enable the Is Trigger on the colliders; for this to work at least one GameObject must have a Rigidbody, the Laser and Enemy are the one being in constant collision so each of them will have there own Rigidbody. Line 27 to 26 will check if we have touch any object that has the Player tag, if is true then I will get the script Player component to call for the method DamagePlayerLives(); if the Enemy is touch by the Laser tag, line 38 to 42, both the Enemy and the Laser object will be destroyed.
Update Player Script
Line 21 shows a new variable created that represent the lives of our Player and a new method, DamagePlayerLives() on line 66, will be called every time Player has contact with a Enemy, reducing a live; when it reaches to 0 the Player dies / gets destroyed.