Learn to code by making a 2D space shooter game.

Suleiman Abdullah
4 min readApr 28, 2022

--

Objective: Enemy Pickups, enemy destroys a pick up when is in front.

In the first step create an empty object inside a smart enemy Laser, and position It to the point where we need to start firing a laser.

In the second step, go to the inspector and add a new layer called powerup.

In the third step, select all powerups and change the layer from default to powerup, but I will change the negative powerup to the default layer since I don't want the Smartenemy to destroy this negative powerup.

In the next step, create the Game object variable and add serialized to it.

Go to the inspector select SmartEnemy <Inspector, drag the laser Start Point to the game object field.

In the next step, create a line renderer component change order in layer to positive 10 for a line to show on top of everything then adjust the index from the start position to show vertical by adjusting the y-axis last check use world space.

Note: disable the line renderer component and not a game object of the line renderer.

Then create a line render variable inside the smart enemy.

In the next step ,select enemy < dgra Line Render < Inspector < line renderer field.

In the fifth step, go to the smart Enemy script and create a layer mask variable called layer mask.

In the next step, select SmartEnemy < Inspector<LayerMask adjust option to power up.

In the sixth step, select the smart enemy holder then override the changes you have made.

In the next step, create a coroutine method called Shot powerup.

In the next step create three variables for origin position, look direction of the ray, and target point where the ray hit.

In the other step, assign this variable to the position where it is needed.

In the next step, we need to fire a ray to detect the powerup, we use RayCastHit2D to do this.

In the next step, create a target position we need a ray to hit powerup we use hitInfo to assign the hitPoint.

In the next step, we need to check if we hit anything, we use hit info to do this.

Note: Raycast2D needs a Boxcollider2D to work.

In the next step, we need to fire a laser if we hit powerup, we need to set the line renderer position first before showing the line.

Then we need to enable the line renderer in order to show since we disable it from the beginning.

In the next step, we need to disable the line renderer after a couple of seconds.

If we hit a powerup, we destroy the powerup, we do this by accessing hit info dot transform dot game object.

Note: Best practice when accessing a component is to null check before accessing it.

In the last step, we need to call our method inside update, remember this is the coroutine we do not call it like a normal function, we call it by type StartCoroutine.

Let's see the final result.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development