Basic enemy behaviour and interaction with the player

Now that we have a mechanism to fire a Projectile and modified its behaviour, it is time to add something to destroy.

Very similar to how we made the Laser Prefab, we prepare a new Prefab for our Enemy.

Just like we did for the Player Movement and Projectile Movement, we create a method for the Enemy Movement.

In this function we assign a new position to our Enemy’s transform position, after having it multiplied with our speed and Time.deltaTime. In our case the direction is specified as downwards.

However, if the Enemy were to go out of the boundaries we’d like him to wrap on the Y-axes and return at the top of the screen. To make it less predictable let’s add a float type ‘randomX’ which returns us a Random Range between two values and assign that to its New Position.

Destroying the Enemy

Now, in case a projectile hits an enemy, we’d like the enemy to be destroyed.
To do that we need to work with a method called OnTriggerEnter().

Add a Tag called Projectile and add it to the Laser Prefab.

Add a Collider and Rigidbody to both the Laser Prefab and the Enemy Prefab.

Make sure to disable ‘Use Gravity’ on the Rigidbody Component
Enable ‘Is Trigger’ on the Collider Component

Make sure to Disable Gravity and to set the Collider Component as a Trigger.

If other GameObjects (with a collider) tagged with “Projectile”, enter its own collider, OnTriggerEnter() will be called and both GameObjects will be destroyed.

Destroying the Player

In order to Destroy our Player we need to create a damage method first.

Add a private variable int to the player script.

Then we create a simple method where each time the Damage() method is called, one life will be subtracted from the player lives and if _lives is less than 1, we destroy the object.

Add a new Tag called “Player” and assign it to the Player.
Just like we did for the Enemy and Projectile, we need to add a Rigidbody and Collider Component.

Last thing we need to do is modify OnTriggerEnter(Collider other). If there is a GameObject present with the Tag “Player”, we cache a reference to the Player and store its transform component in a local variable. Then we perform a null-check to see if there is a player present and execute the Damage() method in case there is.

For now, that is how we set up our Enemy. In the next article we’ll first have a closer look at Instantiating and Destroying GameObjects in Unity.

Good Luck !

Software Engineer — Unity Game Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store