Home and Learn: Games Programming Course

Unity 3D - Fire Cannon

In this Unity tutorial, we're going to get a cannon to fire and demolish a wall. The video below shows you what you'll be doing. The cannon rotates when the mouse is moved; the barrel of the cannon moves up and down when the middle mouse wheel is scrolled; you fire your cannon with a left mouse click.


Start a new project in Unity. Add a Plane to your Scene (Game Object > 3D Object > Plane). Create a material and apply it to the Plane. (See here if you're not sure how to do this. Materials section is halfway down the page)

Now add a cube to your Scene (Game Object > 3D Object > Cube). In the Inspector on the right, add a Rigidbody component to your cube. (If you don't, the cannonball won't knock the cubes down. A Rigidbody adds physics to an object.) Finally, you can add a texture to your cube, if you like. Search for a texture that would be suitable for a castle wall. (You added textures in this lesson: Textures Lesson.)

Now, with the one cube added, duplicate it lots of time and build a wall. (Or just stack a few cubes in a column, if you can't be arsed.) Your Scene might look something like this:

Castle wall in Unity sitting on a green plane

Now we need a cannon so that we can demolish our castle wall.

At the top of Unity, click on the Window menu. From the Window menu, select Asset Store. The Asset Store will launch in your browser. Search for Free Cannon Pack. The one you want is by Storm Bringer Studios and looks like this:

A cannon model in the Unity Asset store

It's a big file size, weighing in at 166 megabytes. But it is an excellent model. Plus it allows you to manipulate the barrel of the cannon separately, which is what we want.

Anyway, download and import it into your Unity project (See here if you're not sure how to do this).

Once you've imported the cannon, click on the Cannon Mini Pack > Prefabs folder:

The Project area in Unity showing a cannon model selected

Select the Small Cannon and drag one into your Scene. Your Scene should look like this:

Cannon in a Unity scene aimed at a wall

We'll get rid of the Animator attached to the cannon. So, in Hierarchy on the left, select your cannon. In the Inspector on the right, click the three tiny circles to the right of the Animator:

The Unity Inspector showing the Animator component

From the menu that appears when you click the circles, select Remove Component:

The Remove Component menu

We'll be firing from the end of the cannon, of course. Rather than using the X, Y and Z coordinate of the end of the cannon, it's easier to create an empty object and position it at the end of the barrel.

So, in the Hierarchy, expand your cannon item. Then select the second Small_cannon item:

The cannon selected in the Hierarchy

Right-click on Small_cannon. From the menu that appears, select Create Empty. Rename the empty object to POF. (Short for Point of Fire). Your Hierarchy will then look like this:

An empty game object created on the cannon

Notice that the empty game object has appeared in the middle of the barrel. Use the Green, Blue and Red arrows to move it to the end. Ours was positioned at these values in the Inspector:


X: 0
Y: 0
Z: 1.2

The barrel of the cannon

OK, that's the setup done. Let's get to the coding.


Unity Fire Cannon Script

In the Hierarchy, select your parent Small_Cannon item:

In the Inspector on the right, click the Add Component button. Type New Script into the search box. Click the New Script item and type FireCannon as the name for the script. Then click Create and Add:

Adding a C# script to a component

By default, Unity places your new script in the Assets folder of the Project area. So, click on Assets in the Project area. Locate your script and double-click it to open it up in your coding editor.

We'll need to set up some variables. So add these to the top of your code, inside of the class:

public GameObject cannonball;
public float cannonballSpeed = 20;
public Transform pof;
public Transform barrel;
public float scrollIncrements = 10;

The first one is a GameObject called cannonball. This is for the cannonball prefab that comes with the cannon you downloaded.

The second variable sets the speed of the cannonball to 20. We've made this public so that you can change the speed in the Inspector.

The third variable is of type Transform. We've called it pof. This will be that empty game object you added to the end of the cannon.

The fourth variable is a Transform as well. It's going to hold the barrel of the cannon.

The final variable is a float called scrollIncrements. This will be use for how much you want the barrel to tilt when the middle mouse wheel is scrolled.

So let's do the mouse stuff first.

In the Update method (you can delete the Start method), add these two lines:

float rotateCannon = Input.GetAxis("Mouse X");
transform.Rotate(0, rotateCannon, 0);

We're using "Mouse X" as the value for Input.GetAxis. This gets you mouse movement. (We did this in the driving game.) Whatever the value is for Mouse X ends up in the float variable we've called rotateCannon.

The second line is one from our driving game, as well - we use the Rotate method on the transform (the transform in this case will be the whole cannon, since this is where the script is). In between the round brackets of Rotate, we have three values separated by commas: the X, Y, and Z values to rotate. We use our rotateCannon variable as the value for Y. The X and Z values can both be zero, as we don't want them to move.

To move the barrel of the cannon up and down, add this line:

barrel.Rotate(Input.mouseScrollDelta.y * scrollIncrements, 0, 0);

This time, the Rotate method is applied to the barrel. In between the round brackets of Rotate, we have three values separated by commas. These:

Input.mouseScrollDelta.y * 10, 0, 0

These are for the X, Y and Z values again. The last two, Y and Z, are both zero. They are both zero because we don't want any movement here. To get the barrel to move up or down, we have this:

mouseScrollDelta.y * scrollIncrements

The mouseScrollDelta.y part gets you the mouse wheel. We're multiplying this by our scrollIncrements variable, which we set at 10.

To fire the cannonball, add this if statement:

if (Input.GetButtonDown("Fire1"))



You'll get red underlined for FireCannonball. That's because we haven't created this method yet. So, add this method, just after the final curly bracket of the Update method:

void FireCannonball() {

Your code should look like this, so far:

Unity C# script to rotate the barrel of a cannon

The technique we'll use to fire the cannonball is to first create a cannonball object (Instantiate it), add a Rigidbody so that it will move, and then set a velocity for it.

So, as the code for your FireCannonball method, add these lines:

GameObject ball = Instantiate(cannonball, pof.position, Quaternion.identity);

Rigidbody rb = ball.AddComponent<Rigidbody>();

rb.velocity = cannonballSpeed * pof.forward;

The first line is this:

GameObject ball = Instantiate(cannonball, pof.position, Quaternion.identity);

Here, we create a GameObject and call it ball. To the right of the equal sign, we use the Instantiate method. This needs three things: the object you want to create (Instantiate), where you want to instantiate your object and, finally, a rotation (basically, Quaternion.identity means no rotation). So, we want to create a cannonball object. We want to create it at the pof position (the end of the cannon, which is that empty game object we created). We don't want any rotation.

To add a Rigidbody to the cannonball, we have this line:

Rigidbody rb = ball.AddComponent<Rigidbody>();

This is the coding version of adding a component through the Unity Inspector. The Rigidybody has the name rb.

The final line is where we get the cannonball moving:

rb.velocity = cannonballSpeed * pof.forward;

Rigidbodies have a property called velocity. We want our velocity to be whatever the value is inside of our cannonballSpeed variable. But we need to multiply this by pof.forward. This not only gets you the direction you want to fire the cannonball but also a Vector3 for the velocity property.

Your code should look like this:

Unity C# script to fire a cannonball from a cannon

Save your work and go back to Unity.

If you have a look at the Project area at the bottom of Unity, and inside of the prefab folder for the cannon, you'll notice that there's a cannonball prefab called Round_shot:

A cannonball selected in Unity

Click on Round_shot to select it. Now, in the Inspector on the right, click the Add Component. Type Sphere Collider in the search box and add one of those:

The cannonball is a bit small. So, in the Transform section of the Inspector, change the Scale values to 1.5:

In the Hierarchy, select your parent cannon again:

In the Inspector, you should see that your Script has a few variables you need to fill:

Notice where the red arrows are pointing, in the image above - to the tiny circles on the right of each variable. Click the first one, for Cannonball. When you click the Cannonball tiny circle, you'll see this box appear:

Click the Assets item at the top. From the list, Double-click the second Round_shot item (the first is for the original prefab). Double-clicking will select an item and close the dialog box down.

Now click the tiny circle for the Pof. You should get the box back up again:

This time, click on Scene at the top. Now double-click the POF item from the list, which is the empty game object the cannonball will be coming from.

Finally, click the tiny circle for Barrel. You'll see this box:

Scroll down to the bottom and locate the Small_cannon item, which is the barrel. (The first Small_Cannon item, the one with the capital C, is the whole cannon.) Double-click to select and close the dialog box. Your Inspector should look like this:

At long last you can try it out! Play your game. Move your mouse to rotate the whole cannon. Scroll your mouse wheel to move the barrel up and down. Press your left mouse button to fire. The video below shows what you should have:


Try changing the speed of the Cannonball via the Inspector to see what impact that has.

One thing you will have noticed is that the cannonballs hang around after you've fired them. If you want, you can make the cannonballs disappear.

To make the cannonballs disappear, go back to your code. Add the following IEnumerator after FireCannonball method:

IEnumerator RemoveCannonball(GameObject ball)

yield return new WaitForSeconds(2f);


Here, we're waiting for 2 seconds until the cannonballs are destroyed. (You can change this to anything you like.)

To call this code, add this line in FireCannonball method, right at the end:


We've covered Coroutine in a different second. But they allow you to pause until you're ready to execute some code.
Your code should look like this: (New lines are highlighted.)

Unity C# script to remove a cannonball

Try it out. You should see that the cannonballs disappear after 2 seconds, as in the video below:



But that's it for this lesson. If you'd like to see some extra tutorials on how to add sound, muzzle flashes, and smoke to your cannon, please get in touch.

<--Back to the Unity 3D Course Contents Page

Email us: enquiry at homeandlearn.co.uk