Unity Beginner to Hero Part 9: Rocket Launcher

Now that we have a fully functional rocket, it’s time to build a launcher for it and start firing. Make a new script, naming it RocketLauncher.cs. Our goal here is to build a script that will allow the player to fire rockets when they click the mouse. The rockets should be spawned pointing in the direction our controller is currently pointing, and there should be a cooldown period between each rocket fired. As per usual, we’ll start with some fields.

public GameObject rocketPrefab;
public Transform rocketBarrel;
public float reloadTime = 0.5f;

private float lastFireTime;

Our first variable is of the type GameObject, and will store a reference to the rocket object that we’re planning to fire. You’ll notice I’ve called it rocketprefab—I’ll cover what a prefab is shortly, and how they’re used in Unity.

Up next is a Transform referencing the rocket’s barrel, which is where the rocket will fire from. After that we declare two floats, one public to represent the cooldown time in seconds, the other private and storing the time that the last shot was fired.

To actually get our rocket to fire, add the following.

if (Input.GetButtonDown("Fire1") && Time.time > lastFireTime + reloadTime)
{
	GameObject go = (GameObject)Instantiate(rocketPrefab, rocketBarrel.position, Quaternion.LookRotation(rocketBarrel.forward));
	Physics.IgnoreCollision(GetComponent<Collider>(), go.GetComponent<Collider>());
	lastFireTime = Time.time;
}

Lots of new things in here. At the top is an if statement, with the first half of it again querying the Input class. We are checking if the button named “Fire1”, has been clicked down. “Fire1” is another of the Unity input presets (which by default maps to the left mouse button), all of which can be changed. In the second half, we see if the current time is larger than the sum of the lastFireTime and the reloadTime. In other words, we see if reloadTime seconds has elapsed since the last shot was fired.

Now for the meat of the code. We declare a new GameObject named go, and assign it to the result of the Instantiate method. Instantiate is a method that creates a new game object in the scene, using an existing game object as a template (the rocketPrefab, in this case). As well, it has additional parameters to set the new object’s position and rotation, which we do. You’ll notice we use something new to set the rotation—a Quaterion. Quaternions are a mathematical structure that Unity uses to store rotations. Most people are familiar with the classic Euler angles method of expressing rotations: x, y and z, or pitch, yaw and roll. Euler angles are very intuitive but run in to some problems when you attempt to interpolate between multiple angles. Quaternions don’t have these problems, but the math behind them isn’t very intuitive. They are represented by four numbers: x, y, z and w, but aside from sharing the same letters they don’t bear much resemblance to Euler angles. How Quaternions work under the hood is beyond the scope of this tutorial.

Yaw, pitch and roll, according to Wikipedia.

But that’s okay, since you very rarely need to know Quaternion math to properly use them in Unity. Typically you will build a Quaternion using one of the static methods that are a part of the class. In the case above, we use LookRotation, which takes a Vector3 in as a direction and outputs a rotation (as a Quaternion) that points in that direction. We’ll talk more about building and using Quaternions in future lessons.

After that, we call a static method from the Physics class named IgnoreCollision. This method takes in two parameters, both colliders, and tells Unity’s physics engine to not register collisions between them. Since our script will be attached to our character, we don’t want the rockets to collide with him right as they fire! Our last line of code sets the lastFireTime to be the current time, ensuring it stays up to date.

Save and apply the script to the controller. Drag the Head object into the rocketBarrel slot, and we’re almost ready to fire. Before we can, however, we need to setup a new prefab for the rocket. In Unity, prefabs are essentially template objects that are saved to your project. These are used for anything that will be needed more than once, or for objects that are creating during gameplay. In this tutorial, we’re going to make a prefab for the rocket we built last lesson, which should still be in the scene.

In the Project panel, go Create->Prefab, and named it “Rocket.” From the Hierarchy, drag your rocket onto the newly created prefab, turning the little grey box blue. (Alternatively, you can just drag the rocket from the Hierarchy anywhere into the Project panel—this will automatically create a new prefab under it’s name.) Lastly, drag the rocket prefab from the Project panel into the rocketPrefab slot on the RocketLauncher component currently attached to the player. You can also delete the rocket that is in the scene—there’s no need for it anymore.

RocketLauncherShooting

At long last, push play and you’re ready to go! Fire away, Cap’n!

Lesson 9 Complete Project


Thanks for reading! If you have any problems with the above tutorial, general comments or suggestions, please post below. It’s always appreciated!

3 thoughts on “Unity Beginner to Hero Part 9: Rocket Launcher

  1. Great tutorial series so far. I’m running into an error at this step. The Console log says:

    Ignore collision failed. Both colliders need to be activated when calling IgnoreCollision
    UnityEngine.Physics:IgnoreCollision(Collider, Collider)
    RocketLauncher:Update() (at Assets/RocketLauncher.cs:22)

    I’ve gone back and copied your script exactly from the “Complete Project” download.

    RocketLauncher.cs is attached to the Character, with the “Rocket” prefab added in the rocket slot and the Head(Transform) in the Rocket Barrel slot.

    The Rocket prefab has a sphere collider component attached. The “Capsule Collider” on the Character is unchecked, and the Character Controller is added and checked from the previous tutorial. I tried checking the “Capsule Collider” back on. This does cause the error to go away – but then nothing happens as far as firing the rocket.

    The Head is parented to the Character. I’ve tried adding a collider to that, and it didn’t really seem to change anything.

    Any thoughts?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s