Making An Asteroid Shoot Towards The Player!

Apart from the enemy spaceships, I want some more dangerous things in my game. Let’s make some Asteroids to avoid!

Vincent Taylor
Jul 24, 2021

Today’s Objective: Create an asteroid that spawns occasionally, shoots towards the player from a random angle, and the player must avoid otherwise they will die with 1 hit.

First, the prefab:

Create a new 2D Sprite GameObject called “Shooting Asteroid”. I’m going to use the same movement script as my enemy ships, since its mostly identical code, but add some modifications.

Set the sprite, add the movement script, and a Trigger 2D collider
I also set the tag to “Enemy” since it will be detected the same as an enemy ship on collision
I save it as a prefab, and delete the “Shooting Asteroid” GameObject in the scene

In the EnemyMovement script:

I add these additional variables
I add these public functions to set the variables when spawned
Now I update the movement code in my Update method to use the direction variable instead of forcing it to go down
I make sure Asteroids will never be returned to the top when the exit the bottom of the screen, by adding a boolean check into the existing code in Update()

Now, moving to my SpawnManager script:

Using mostly the same variables needed for enemy spawning, I create a seperate process for spawning ShootingAsteroids
Different from spawning enemies, the Asteroid code also has to change the default variables to suit an Asteroid
I use this function to create a random spawn position for the Asteroid, with the wide horizontal range creating the diagonal angle of direction towards the player

After adding the Asteroid to the new “Asteroids” spawn list on the Spawn Manager’s Inspector window, it combines with the rest of the game to make this:

Enemies that dodge, asteroids that kill, and lasers that hurt!

--

--

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.