Nerd For Tech
Published in

Nerd For Tech

Making Enemy Shoot when behind Player

Day 48- Making 2D Space Shooter Game

Objective: Make enemy detect when it is behind player and turn around and shoot

Let us start by spawning a new type of enemy that is going to show these kinds of behavior.

Now create a new script that is going to create a behavior for your new type of enemy.

Inside the script, declare all the necessary variables that are going to be needed during the process. Add them as you add functionalities per need.

Now take a reference to the player script and player transform for the location of player.

Now in your Update function, set your enemy condition to rotate when the enemy is below player and set rotation to default if not.

Call your movement function to move enemy down with each frame and lastly add a condition to fire only when enemy and player both are alive.

Player moves down when called and after it goes outside bounds in y-axis, it resets the position at top to move downwards again at random position in x-axis between the range of -9 and 9.

Now when the enemy location is below that of player, check if the player is within the radius of two from the enemy in x-axis. If returned true then rotate the enemy to look towards the opposite direction else set the rotation to default.

Here, instantiate the laser when enemy fires laser, then check where the laser is being instantiated. if it is positive 0.6 from the enemy current position then that means the enemy has rotated and looking up towards player so set the laser motion to up by calling FireUp function in laser script and vice versa.

In the laser script, create a dir variable and set its default value to -1 so it moves down by default and when the function is called, the direction of laser motion changes accordingly.

Finally, move your laser upwards or downwards depending on the value of dir variable. By default, it will move down and when the public function FireUp is called, dir value becomes positive and starts moving upwards and vice versa.

And this is the final result.

--

--

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