Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Mike Geig, an experienced teacher and game developer, with a foot firmly in both camps who currently teaches game design and development at Stark State College and the Cleveland Institute of Art. Mike also works as a screencaster for Unity Technologies and is a member of Unity’s Learn department.

Many games require guns and projectiles of some sort. Everyone once in a while though, your fun-of-the-mill gun just won’t suffice. What you then need is a laser. Creating laser gun effects in Unity is rather simple once you know how to use Rays, Line Renderers, and a little bit of scripting.

To complete this post, you should have a basic knowledge of Unity, including how to create and position basic game objects in a scene. If you need help with any of that, try the Game Development Essentials with Unity 4 LiveLessons video and the Learning Game Development with Unity video.

Setting up the Scene

Before you can go off just shooting lasers all willy-nilly in your game, you need to spend some time setting up the scene. Since the scripting component is the interesting part of this article, let’s just cover this step quickly:

  1. Create a new scene.
  2. Add a plane to the scene (GameObject->Create Other->Plane) and position it at (0, 0, 0).
  3. Add a cube to the scene (GameObject->Create Other->Cube) and position it at (0, .5, 0). Add a rigidbody to the cube.
  4. Add a directional light to the scene (GameObject->Create Other->Directional Light).
  5. Add another cube to the scene and position it at (.4, 1, -10). Give it a scale of (.1, .1, 1). This is optional, since it just gives us a graphical gun body.
  6. Create an empty game object (GameObject->Create Empty) and name it “GunTip.” Position it at (.4, 1, -9.5). This object will be responsible for actually emitting the laser. It will be positioned right at the tip of the gun object created in step 5 (if you did that part).

Your scene should now look something like this:

laser.Cap1

The Laser

To create a laser effect in Unity, we will be using something called a Line Renderer. This is a special type of renderer that takes two (or more) points and draws a line between them. The reason we created an empty game object (“GunTip”) before is because a line renderer won’t work if we have another type of renderer already on the object.
Let’s add and configure our line renderer now. You will see it appear as a flat line near the origin of the scene. Don’t worry. We will be writing a script to make this behave exactly as we would like:

  1. With the “GunTip” object selected, add the Line Renderer (Component->Effects->Line Renderer).
  2. Set the “Start Width” and “End Width” parameters both to .1

You are now 2/3rds of the way to raining down light-emitted havoc upon your enemies.

The Laser Script

Let’s create the script that will be controlling the madness. We will look at the script piece by piece, and the entire script will be listed at the end.

We’ll start by creating a C# Script. Name the script “LaserScript” or something else appropriate (or not; you can name it “Banana” for all I care). Attach the script to our “GunTip” object (click and drag it onto the object). Now let’s look at the script:

This is the standard rigmarole that was created for you. Nothing to see here.

We then create a LineRenderer variable named “line,” which will hold a reference to the line renderer attached to our GunTip. Inside our Start() method, we find the line renderer component and assign it to our variable for safe keeping. We then disabled it (no sense seeing the laser when we aren’t firing it):

In our Update() method, we check to see if the player has pressed the “Fire1” button. This, by default, resolves to the left mouse button. Feel free to substitute any button you want here, but the left mouse button just feels right, ya know? If the player presses the Fire1 button, we will first stop a coroutine named “FireLaser” (this hasn’t been written yet – we will get to that next). We stop the coroutine as a precaution. The way this is written, it should never be necessary. Still, better safe than sorry. Finally, we start our “FireLaser” co-routine. This will handle the continual firing of our laser:

This is our FireLaser() method (the one mentioned previously). This will handle sustaining our laser and also impacting anything the laser touches. The first thing we do in the method is turn our laser on. Then we start a while loop. This loop will continue iterating while the player continues to hold the Fire1 button down (notice how this is GetButton instead of the GetButtonDown that was used in the Update() method). Inside this loop we are creating a ray that starts at our “GunTip” object and aligns with its forward direction. We then declare a RaycastHit variable (foreshadowing). Finally, we set one end of our line renderer to the origin of the ray (the tip of the gun):

We then shoot our ray out using Physics.Raycast. Raycasting is actually overkill for this example. Since the gun never moves, we could just determine the end point of the laser and use it. The reason we do it this way is in case you actually want to use the laser in a real, moving, video game (gasp). Also, hitting objects with the laser would be next to impossible without rays. In this example, we shoot the laser out 100 units (an arbitrarily selected number). The Raycast() function will return a Boolean value indicating whether or not the ray hit anything. If it did, our variable “hit” will contain all of the info. If the ray doesn’t hit anything, then we place the other end of the line renderer 100 units along the ray (boring). If the ray does hit something, however, we first set the end of the laser to the point that the ray hit. Then, we determine if the object hit has a rigidbody (spoiler alert: it does). If it does, we add force to it along the direction that the laser is facing. We end this while loop with a “yield return null” statement that will cause this loop to pick right back up the next time this object updates. The last thing this co-routine does is turn the laser back off.

Here is the full script:

Blowing Stuff Up

Go ahead and run your scene. You should be able to shoot your cube now (no mercy). So you might be wondering where to go from here. Two things readily come to mind:

  1. The laser is kind of boring (grey, eww). Try creating a new, colorful (laser-like?) material to put on the line renderer. Hint: the best materials for line renderers use the “Particle” shaders.
  2. Attach the GunTip to the gun and attach the gun to the main camera of a first person controller. Now you have all of the makings of a First Person Shooter.

There are many other ways to turn this into a laser fest of Techno-Rave Party proportions. Have Fun!

laser.Cap2

Look below for some great Unity resources from Safari Books Online.

Not a subscriber? Sign up for a free trial.

Safari Books Online has the content you need

Learning Game Development with Unity 3D introduces you to the fundamentals of 3D game design with the Unity engine. This tutorial is designed with the absolute beginner in mind; no prior experience with Unity is required.
Advanced Unity 3D Game Development teaches you how to use some of the advanced features available to you within the Unity 4 game engine. This course is designed for the experienced Unity developer. You should have a working understanding of the Unity 4 engine and features before taking this tutorial.
Learning C# by Developing Games with Unity 3D Beginner’s Guide starts by explaining in simple terms the three concepts you need for writing C# code and scripts: 1) variables to hold information; 2) methods (functions) to use the information; and 3) Dot Syntax to communicate the information where it’s needed. The book builds on these concepts to open up the world of C# coding and Unity scripting. You will use this new power to access the features provided in Unity’s Scripting Reference.
Game Development Essentials with Unity 4 LiveLessons demonstrates the power and versatility of the Unity 4 engine and helps you leverage this engine in your own game development endeavors. Geig covers the Unity interface, concepts of 2D and 3D game development, building terrain for your games, as well as developing game objects that interact through collision. You will also learn to work with scripts and manipulate objects through code. And for those of you who want to develop for mobile devices, you will find coverage here as well. Finally, the course ends with a lesson on how to construct your own game with the Unity 4 game engine.
Game Development for iOS with Unity3D takes you through the complete process of Unity iOS game development. A game developer for over 12 years, the author presents production-proven techniques and valuable tips and tricks needed to plan, build, test, and launch games for the iPhone, iPod, and iPad. He walks you through all the necessary procedures, including how to publish your game to the App Store.

About the author

Me-1131-Edit Mike Geig is both an experienced teacher and game developer, with a foot firmly in both camps. He currently teaches game design and development at Stark State College and the Cleveland Institute of Art. Mike also works as a screencaster for Unity Technologies and is a member of Unity’s Learn department. His Pearson video, Game Development Essentials with Unity 4 LiveLessons is a key title on Unity. Mike was once set on fire and has over a million “likes” on Facebook and can be reached at @mikegeig.

Tags: gameobject, Lasers, Line Renderer, scenes, script, Unity, Unity 4, unityengine,

Comments are closed.