Adding Asteroids

Gert Coppens
3 min readAug 8, 2021

--

The idea is that the Player has to avoid the Asteroids spawned by the SpawnManager. Asteroids will damage the player on impact but can be destroyed by shooting them, in addition they’ll be responsible for dropping items. In this article we’ll have a look at manufacturing the basic Asteroid Behaviour.

Objective:

Creating randomly spawning Asteroids that while moving in a downward motion, rotate in a random direction.

Necessities:

  • Empty “Asteroid” script
  • A prototype for the Asteroid GameObject

Solution:

The Asteroid behaviour is actually very similar to our Basic Enemy behaviour we introduced earlier, click here for more information. However, additionally we need to construct a method that is responsible for assigning a random rotation to each Asteroid Object.

Logic:

This is our basic Asteroid script. See if you can read through this script and comprehend the logic, it should be very clear to you by now if I’m not mistaken.

If you’re just tuning in, feel free to take a look at the previous articles on this medium dev blog where you’ll be introduced to Unity and Unity C# step-by-step.

Adding a Random Rotation

Now we just need to add a random rotation to the AsteroidMovement() method. We could do that by using transform.Rotate().

random.rotation * times per frame

In the RandomRotation() method we basically assign a random rotation for the X and Y fields of transform.Rotate(x, y, z). Notice how we pick a range between zero and 5 and multiply that with 90 before returning a value. Random.Range for integers is inclusive/exclusive for it’s range (inclusive for floats to Random.Range((0.0f , 5.0f) can return 5), so it will return a number from 0 to 4. Multiplying this by 90 will give you one of 0, 90, 180, 270.

Destroying the Asteroid

Next we have to add OnTriggerEnter() to our script, click here for more information about this function. If the other collider tagged “Player” collides, destroy this object, if other collider is tagged “Projectile”; destroy Projectile, do fun stuff, destroy this.Asteroid.

Now we have a basic script for our Asteroids and in the following articles we’ll be adding more logic to this function, such as logic for explosions and item drops. Piece by piece we get to see the Space Shooter Project take form.

Previous | Next

--

--

Gert Coppens

Software Engineer — Unity Game and Application Developer