New Enemy Movement for Laser Enemy — 2D Galaxy Shooter in Unity!

Objective: To give our new laser enemy some new movement!

Let’s now setup some new movement for our last enemy to be implemented in the 2D Galaxy Shooter. As this enemy is going to have the laser beam feature, I decided the best movement for them would be smooth left to right whilst moving up and down(sine wave):

When the enemy reaches one side of the screen boundaries, they will respawn out the other side and start again. Let’s jump into it!

Let’s Create Some Code — Enemy 3

Let’s now work on some sideways movement for the laser enemy:

Let’s create a few variables that are going to be used for the enemies speed, the frequency of the waves, the magnitude (or min and max height-amplitude) of the waves, a regular spawning point on the X-axis and a right boundary point for our positional If check statement. Frequency is going to look at how many waves per cycle (the lower the number the less waves and vice versa).

We also need a Vector3 variable that is going to cache the transform.position of the enemy and we are also going to cache the _spawn Vector3 variable as we are going to reuse this.

In Start() let’s assign the _pos variable to the transform.position (which we are going to use in the movement method). Let’s also assign the _spawn variables cached data and then assign the enemies transform position to _spawn.

Let’s call our LaserEnemyMovement() method in the Update() method as we want it to be constantly getting called.

Next, let’s move the enemies position to the right multiplied by the enemies speed and Time.deltaTime to make it move in real time.

Then we are going to assign the laser enemies trasform.position to the above position plus transform.up. We are going to multiply this by Mathf.Sin() method that takes the Time.time parameter multiplied by the frequency and then finally by multiplying it by the magnitude to get the below result:

Let’s also take a look at a higher frequency of say 10:

Let’s also look at a higher magnitude (amplitude) of the wave. I have used 3:

There is also an If check to see when the enemy reaches 9.5 on the x-axis and when it does it is going to respawn back to the left hand side:



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