How To Make A Game Like Bomberman With Unity

Ever want to blow up your friends? Learn how to make a game like a Bomberman with Unity 3D in this step by step tutorial that will have you setting bombs off with ease. By Brian Broom.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 3 of this article. Click here to view the first page.

Add a LayerMask

The walls in the game are, luckily, bombproof. The bombs are not bombproof, and the players are definitely not bombproof. You need a way to tell if an object is a wall or not. One way to do that is with a LayerMask

A LayerMask selectively filters out certain layers and is commonly used with raycasts. In this case, you need to filter out only the blocks so the ray doesn’t hit anything else.

In the Unity Editor click the Layers button at the top right and select Edit Layers…

EditLayersButton

If necessary click on the expansion triangle in front of the word Layers to expand the list of layers if it is not visible.
Click the text field next to User Layer 8 and type in “Blocks“. This defines a new layer you can use.

BlocksLayer

Inside the hierarchy view, select the Blocks GameObject, inside the Map container object.

BlocksGameObject

Change the layer to your newly created Blocks layer:

SelectBlocksLayer

When the Change Layer dialog comes up, click the “Yes, change children” button, to apply to all of the yellow blocks scattered across the map.

ChangeLayerDialog

Finally add a public reference to a LayerMask so the Bomb script will be able to access the layer by adding the following line just below the reference to the explosionPrefab.

public LayerMask levelMask;

Don’t forget to save your code.

Bigger! The Explosions Must be Bigger!

The next step is to add the iconic touch of expanding rows of explosions. To do that, you’ll need to create a coroutine.

People often confuse coroutines with multi-threading. They are not the same: Coroutines run in the same thread and they resume at intermediate points in time.

To learn more about coroutines and how to define them, check out the Unity documentation.

Note: A coroutine is essentially a function that allows you to pause execution and return control to Unity. At a later point, execution of that function will resume from where it last left off.

Return to your code editor and edit the Bomb script. Under Explode(), add a new IEnumerator named CreateExplosions:

private IEnumerator CreateExplosions(Vector3 direction) 
{
  return null; // placeholder for now
}  

Create the Coroutines

Add the following four lines of code between the Instantiate call and the disabling of the MeshRenderer in Explode():

StartCoroutine(CreateExplosions(Vector3.forward));
StartCoroutine(CreateExplosions(Vector3.right));
StartCoroutine(CreateExplosions(Vector3.back));
StartCoroutine(CreateExplosions(Vector3.left));  

The StartCoroutine calls will start up the CreateExplosions IEnumerator once for every direction.

Now comes the interesting part. Inside of CreateExplosions(), replace return null; // placeholder for now with this piece of code:

//1
for (int i = 1; i < 3; i++) 
  { 
  //2
  RaycastHit hit; 
  //3
  Physics.Raycast(transform.position + new Vector3(0,.5f,0), direction, out hit, 
    i, levelMask); 

  //4
  if (!hit.collider) 
  { 
    Instantiate(explosionPrefab, transform.position + (i * direction),
    //5 
      explosionPrefab.transform.rotation); 
    //6
  } 
  else 
  { //7
    break; 
  }

  //8
  yield return new WaitForSeconds(.05f); 
}

This looks like quite a complicated code snippet, but it's actually fairly straightforward. Here's a section-by-section explanation:

  1. Iterates a for loop for every unit of distance you want the explosions to cover. In this case, the explosion will reach two meters.
  2. A RaycastHit object holds all the information about what and at which position the Raycast hits -- or doesn't hit.
  3. This important line of code sends out a raycast from the center of the bomb towards the direction you passed through the StartCoroutine call. It then outputs the result to the RaycastHit object. The i parameter dictates the distance the ray should travel. Finally, it uses a LayerMask named levelMask to make sure the ray only checks for blocks in the level and ignores the player and other colliders.
  4. If the raycast doesn't hit anything then it's a free tile.
  5. Spawns an explosion at the position the raycast checked.
  6. The raycast hits a block.
  7. Once the raycast hits a block, it breaks out of the for loop. This ensures the explosion can't jump over walls.
  8. Waits for 0.05 seconds before doing the next iteration of the for loop. This makes the explosion more convincing by making it look like it's expanding outwards.

Here's how it looks in action:

BombExplosionDiagram

The red line is the raycast. It checks the tiles around the bomb for a free space, and if it finds one then it spawns an explosion. When it hits a block, it doesn't spawn anything and it stops checking in that direction.

Now you can see the reason why bombs need to be snapped to the center of the tiles. If the bombs could go anywhere, then in some edge cases the raycast will hit a block and not spawn any explosions because it is not aligned properly with the level:

AllignedVsNot

Finally, select the Bomb prefab in the Prefabs folder in the project view, and change the Level Mask to Blocks.

BlocksLevelMask

Run the scene again and drop some bombs. Watch your explosions spread out nicely and go around the blocks:

ExplosionSpread

Congratulations, you've just made it through the hardest part of this tutorial!

Go ahead and reward yourself with a refreshing drink or a delicious snack, think about what you just did, and then come back to play around with reactions to explosions!

Chain Reactions

When an explosion from one bomb touches another, the next bomb should explode -- this feature makes for a more strategic, exciting and firey game.

Luckily this is quite easy to implement.

Open up the Bomb.cs script in your code editor. Add a new method named OnTriggerEnter below CreateExplosions():

public void OnTriggerEnter(Collider other) 
{

}

OnTriggerEnter is a pre-defined method in a MonoBehaviour that gets called upon collision of a trigger collider and a rigidbody. The Collider parameter, named other, is the collider of the GameObject that entered the trigger.

In this case, you need to check the colliding object and make the bomb explode when it is an explosion.

First, you need know if the bomb has exploded. The exploded variable will need to be declared first, so add the following right under the levelMask variable declaration:

private bool exploded = false;

Inside OnTriggerEnter(), add this snippet:

if (!exploded && other.CompareTag("Explosion"))
{ // 1 & 2  
  CancelInvoke("Explode"); // 2
  Explode(); // 3
}  

This snippet does three things:

  1. Checks the the bomb hasn't exploded.
  2. Checks if the trigger collider has the Explosion tag assigned.
  3. Cancel the already called Explode invocation by dropping the bomb -- if you don't do this the bomb might explode twice.
  4. Explode!

Now you have a variable, but it hasn't been changed anywhere yet. The most logical place to set this is inside Explode(), right after you disable the MeshRenderer component:

...
GetComponent<MeshRenderer>().enabled = false;
exploded = true;        
...  

Now everything is set up, so save your file and run the scene again. Drop some bombs near each other and watch what happens:

ChainReaction

Now you've got some seriously destructive firepower going on. One little explosion can set your little game world on fire by triggering other bombs, allowing for these cool chain reactions!

The last thing to do is to handle players' reactions to explosions (Hint: they're not good!) and how the game translates the reaction into a win or draw state.

Brian Broom

Contributors

Brian Broom

Author

Eric Van de Kerckhove

Author and Team Lead

Gijs Bannenberg

Tech Editor

Chris Belanger

Editor

Sean Duffy

Final Pass Editor

Over 300 content creators. Join our team.