So far, we've taken a look at what other developers, large and small, are doing with Unity. We talked about what it's going to take for you as a small developer to succeed to finish a fully functional game. Now it's time to roll up your sleeves, tie up your inner procrastinator and lock it in the trunk of your car, and start learning to build a game with Unity.
Here's what we're gonna do:
Come up with a game idea
Distil it down to that small, singular piece of joy
Start building the game in Unity using placeholder objects
Add lighting to the scene
Tie into Unity's built-in physics engine
Modify a GameObject using components to bend it to your steely will
Let's get cracking!
Open Unity 3D. The last project you had opened should appear. (This might be the AngryBots Demo from Chapter 1, That's One Fancy Hammer!).
In the menu, click on File | New Project….
Under Project Location, type in or browse to the folder where you want your project created. It's a good idea to create a new folder somewhere on your computer where you'll be able to find it again, and name it something that makes sense. I created a folder on my desktop called
Unity Games, and created my new project in an empty folder called
Unity gives us the option to import a bunch of useful premade goodies into our new project. Select the
Character Controller.unityPackagefile checkbox to import it as shown in the following screenshot:
Next, click on the Create button. Unity will briefly close and restart. After importing the assets we selected, the program will open.
Close the Welcome to Unity start screen if it's open. You'll find yourself staring face-to-face with that wide-open 3D plane.
If you're staring at nothing but a 3D plane in the Scene view, Unity has pulled a switcheroo on you. To get back to a layout like the one you saw in the AngryBots Demo, choose 2 by 3 from the Layout drop-down at the top-right of the screen. Note that there are other choices here, and that Unity enables you to save and restore your own custom layouts.
What kind of game are we going to make? Well, let's pretend that you are totally pumped up about volleyball (work with me here). All you can think about night and day is volleyball. You dream about it at bedtime. You play it every chance you get. So, when it comes to making your first game in Unity, there's no question: you have to make a volleyball game.
Let's back away from that idea a little and, using what we learned in Chapter 2, Let's Start with the Sky, evaluate the difficulty level of a volleyball game. Volleyball features two teams of six players on either side of a net. A server hits a ball with his hands over the net, and the teams compete to keep the ball in the air, hitting it back and forth over the net. The rally ends when:
One team lets the ball hit the floor
The ball goes out of bounds
An angry puma bursts onto the court and starts chewing on the star player
The first team to score 25 points wins the set. A match is best-of-five. Then there are a number of rules that govern how often and in what way a player may hit the ball (hint: no grabsies).
Hopefully, it's clear that volleyball is a BIG game with lots of rules and a heaping helping of complexity. Multiple teams mean that you have four options:
Two-player, same computer, both players share the keyboard and mouse to compete against each other
One-player, same computer, so, you'd have to program AI artificial intelligence to enable the computer to play against a human
Two-player, different computers
Multiple players, multiple computers, where every human player controls a team volleyball team member
We saw in the last chapter that these multiplayer options can add significant layers of complexity to a simple game. Right out of the gate, the challenge is daunting. In addition to providing for two teams, having multiple players on each team means that you have to program a way for the player to switch between different characters. And who knows how you're ever gonna animate that puma?
All this results in the simple mathematic equation: You + volleyball game = badIdea^10. That's a bad idea to the power of ten, which (mathematically) makes it an exponentially bad idea.
But, volleyball is your passion. Does that mean you can never follow your dreams and make the kinds of games you'd always hoped to build? Of course not! Let's see if we can distil the game of volleyball down to its barest essentials to that small, singular piece of joy.
Scrap the sets and the best-of-five match structure.
Kibosh the teams.
Jettison the multiple players.
Ditch the net.
Nix the referee and the spectators.
What do we have? Just a person with a ball, looking kind of lonely. Hmm. That person might be a little tricky to model, texture, rig, and animate. Let's keep slashing.
Next, trash the player.
Now where are we? We have a ball, floating in midair; a ball that can't hit the floor. So, we need something simple to hit the ball with. A human character is too complicated, so let's just say it's a surface. We'll have some kind of thing that we can bounce the ball on.
You know what? This game is starting to sound a lot like keep-up. You might have played that as a kid with a balloon that couldn't hit the ground. Or you might have played it in a circle of hippies and called it Hacky Sack or footbag. You might have played it in a soccer drill by bouncing the ball on different parts of your body. You may even have played it by taking something scalding hot out of the oven, calling it "Ow! Ow! Ow! It burns! Get me an oven mitt already! OW!"
Keep-up looks a whole lot like Pong or Breakout from Chapter 2, Let's Start with the Sky. You have an object to keep up and an object to keep it up with. The innovation is a little bit of physics in this case, gravity, which is the force that constantly pulls the object toward the ground. It's simple, it's effective, and your players will instantly get it. It distills volleyball down to that singular piece of joy. It's what volleyball was meant to be, before Johnny McBuzzkill came along and added all of those formalized rules and unflattering shorts. And, because little kids play and enjoy keep-up, you know that you're tapping into some primal, intuitive game mechanic that will stand the test of time.
Keep-up sounds like a great first project for learning Unity. Let's do it! Let's build a keep-up game!
For now, we'll use Unity's built-in 3D primitives to create our
Game objects. Aside from the terrain editor, Unity doesn't have any great modeling tools built in. You'll need a piece of 3D software for that. Let's see what we can manage with what Unity gives us. Add a built-in GameObject to the Scene:
In the menu, click on GameObject.
Point to Create Other and then click on Sphere.
Well, yeah, actually! Unity has a number of prebuilt simple 3D models, also known as primitives, which we can use to get started. You've just created a built-in Game object with four components on it. Look at the Inspector panel to see what those components are:
Let's make a few changes to our ball. We should rename it and move it up into the "air" so that it has some place to fall from.
In the Hierarchy panel, find the Game Object below Main Camera called Sphere.
To rename the Sphere, you can either right-click/alternate-click on it and click on Rename, or press F2 on the keyboard if you're on a PC. Mac users can press the Return or Enter key to rename the Sphere. You can also rename a Game Object by selecting it and typing a new name into the field at the top of the Inspector panel.
Rename the Game Object as Ball.
Your project can fill up fast with generically named Game Objects and other assorted things, so let's stay on top of our project by naming Game Objects as we create them.
The center of your game world is called the origin. The origin is the magical place in 3D space where everything begins. 3D space is divided up by X, Y, and Z axes. If you remember your Cartesian grid from grade school, or if you've ever seen a bar or line graph, the X-axis runs one way (usually horizontally), and the Y-axis runs perpendicular to it (usually vertically). 3D is like taking a second piece of paper and sticking it at right angles to your graph so that you have a third axis firing straight up at your face from your desk, and down into the floor in the opposite direction.
The orientation (the way the X, Y, and Z axes are positioned) varies from program to program. Unity has a Y-up orientation. The X and Z axes run perpendicular to each other on the "floor". If you hold your arms out like a scarecrow, your arms are the X axis, and the Z axis runs through your belly button. The Y axis runs straight up into the sky, and straight down to the center of the Earth where there are probably goblins or some such creatures.
Let's get a better look at that ball. To orbit around the Scene view, hold down the Alt or Option key on your keyboard (depending on whether you're using a PC or a Mac) and press and hold the left mouse button. If the ball is centered near the origin, you should notice that the "ground" plane slices right through it. That's because the ball's transform ("registration" or "pivot point" in other software) is at its center. Half the ball is above ground, half the ball is below. If the ball's X, Y and Z position values are all zero, the center of the ball is at the origin, where the three 3D planes converge. It's entirely likely that your ball is floating around somewhere else in the Scene. Let's fix that right now.
If you ever get lost orbiting, panning, and zooming around the Scene view, remember that you can reorient yourself by clicking on the gizmo at the top-right of the Scene view. Click on the green Y cone to view the scene from the top-down. Click the red X cone to view the scene from the right. Clicking on the blue Z cone focuses us at the front of the Scene. Click the gray box in the middle of the gizmo to return to a perspective view. If you want to completely reverse your view, you can click on the white cone sitting opposite to your orientation doing this will flip the view around so that you're looking at things from the opposite angle. The label beneath the cone tells you which view you're currently using.
If you've ever listened to your science or art teacher drone on about color spectrum of light, you might have noticed that X, Y, and Z map onto Red, Green, and Blue. Red, Green, and Blue are the primary colors of light, and are always listed in that order. If you're visually-oriented, it might help you to know that X is Red, Y is Green, and Z is Blue when you're looking at any depiction of axes in Unity. Most often, your selected axis turns yellow when you hover over or select it.
Make sure that the Ball Game Object is selected. Click on it in the Hierarchy panel.
See the control gizmo poking out from the center of the ball? You can either click-and-drag the green Y-axis to move the ball up, or type a new Y position for it in the Inspector panel. As we want to stay on the same page together, let's type it. Look in the Inspector panel and find the Y field it's next to Position in the Transform component of the Ball.
Change the Y position from 0 to 2.
Press the Enter key to commit this change.
Your ball may not have begun life at the origin. Make sure that the values for its X and Z position are at 0.
The units in our 3D world are arbitrary. When you're working on your game, it may help to ascribe real-world measurements to these units. Perhaps one unit equals one foot or one meter? If you're building a real-time strategy game where the scale is much larger, maybe one unit equals one mile or one kilometer? The Ball that we've just created is a little large for our purposes, so let's shrink it down a touch.
With the Ball still selected type 0.4 for the X, Y, and Z scale values in the Transform Component of the Ball.
Press Tab to move the carat to each new field, and press Enter after typing in each field to commit the change.
The Ball should shrink down to 0.4, or 40% of its original size. Note that if you enter 0.4 only into one or two of the three Scale fields, you'll accidentally create a weird-looking egg or an ovoid-shaped ball.
A computer teacher of mine once gave me sage advice: save often, cry seldom. Throughout the book, I won't pester you to save your project in every other paragraph that's up to you and how comfortable you feel with your dodgy power cable and the fact that you're reading this book during a lightning storm. At the very least, let's learn how to save the Scene that we're working on. Save frequency is up to you from this point on!
Click on File | Save or Save Scene As in the menu. You're asking Unity to save the current named Scene, but there really is no named Scene for it to save yet. Let's fix that.
In the resulting dialog, type a name for your Scene. I chose to call mine Game.
Click on the Save button. Unity actually creates a Scene asset in the Project panel called Game. You know that it's a Scene because it has a Unity 3D icon next to it.
Now that you've named your Scene, you can quickly save changes at any point by pressing Ctrl or Command + S, or by clicking File | Save Scene in the menu. Clicking File | Save Project will do a blanket save across your entire project.
We'll borrow a term from Pong to name our hittable surface "paddle". The paddle will be the thing the player uses to bounce the ball and keep it up in the air. We can build the paddle using Unity's built-in Cube primitive, like we did with the Sphere.
In the menu, choose Game Object | Create Other | Cube.
Now, according to Hierarchy, we have three instances of GameObject in our Scene: the Ball, a Cube, and the Main Camera. Let's rename our Cube to remind us what it will do in the game.
If the Cube is not selected, click on its name in the Hierarchy panel.
Now, we should make the Paddle more paddle-like by changing the Scale properties of the Transform component.
Make sure that the Paddle is still selected in the Hierarchy panel.
In the Inspector panel, change the X Scale value of the Paddle to 1.1.
Change the Y Scale value of the Paddle to 0.04. Make sure the Position values are zeroed out to move the Paddle to the origin.
Although technology is constantly changing, most often a piece of 3D artwork comprises three types of pieces: vertices, edges, and faces. A vertex is a point in 3D space. The Paddle that we just added has eight vertices (points) one on each corner. In these illustrations, we'll depict a cube mesh to make this easier to grasp.
3D models, then, are made up of three-sided (or sometimes four or more-sided) surfaces. A multisided shape is called a polygon. When you hear someone say polygon count, he's talking about the number of triangles that make up a 3D model. The fewer the polygons, the less work the computer needs to do to render, or draw, the model. That's why you may have heard that game artists need to produce low-polygon (or low-poly) count models, while film and teevee artists are free to produce high-poly count models. In film or teevee, a shot only has to be rendered once before it's committed to a frame of the movie forever. But, video game engines such as Unity have to constantly draw and redraw models on the fly. The fewer the polygons, the faster the game will potentially run.
A low-polygon model looks more crude and roughly-hewn than a high-polygon model. As video games are built for better and faster systems, the models start featuring higher-polygon counts. Compare the character models in a game like Half-Life with the higher-polygon count models in the game's sequel, which required a faster computer to run it. The difference is clear!
The number of polygons that Unity can handle in a single Scene really depends on the hardware that's running your game. Unity games are hardware-accelerated the faster the machine that runs your game, the more polygons you can push. The best thing to do is to build your models with as few polygons as you can get away with, without making your game a giant cube-fest (unless you're making Minecraft, in which case, more power to you). Decide on a minimum system specification, then test early and often on that minimally-powered system to ensure that your game actually runs!
Of course, it entirely depends on your game, but you might try staying between 1,500 and 4,000 triangles per mesh to keep things humming.
Keep in mind that a number of factors beyond polygon count determine how quickly or slowly your game runs. Learning how to put together a lean, mean, and optimized game is something you'll learn over time as you gain experience as a game developer.
When you bring a 3D model into Unity from another program (as you'll be doing later in this book), Unity converts the model's whatever-gons into triangles. When you read about model architecture in Unity, "triangles" is the term that will crop up most often.
If you've kept an eye on the Game view, which is what the player sees, you've noticed that the Mesh Game Objects in our Scene are a dark, dreary gray color. Would you believe me if I told you they're actually closer to white?
Just like on a real movie or teevee set, 3D scenes require lights to illuminate objects. The lights aren't actually "real" objects (like our Ball and Paddle meshes) they're virtual objects in 3D space that determine whether the faces on a mesh will appear bright or dark. The computer figures this out for us based on the kind of light we use, the way we position and rotate it, and the settings we give it.
So, while you can move a light around your scene just like the Ball or the Paddle, there's no actual geometry or triangles comprising the light. Lights aren't made of triangles, they're made of data. In Unity, as in many 3D programs, lights are represented in the Scene view by icons (or as Unity calls them "gizmos"), with lines indicating their direction or their area of influence.
In the Scene view frame, click the Wireframe button and switch to Textured rendering. Then click on the little light icon (it looks like a sun) a few buttons over to see the effects of our (as-yet-non-existent) lighting. Your ball and paddle should look as dreary and dark gray as they do in the Game view.
In the menu, click on Game Object | Create Other. The three types of lights that Unity supports are listed there: point light, spotlight, and directional light.
A new directional light is added to the Scene. The icon also looks like a little yellow sun. When the light is selected (as it is now), a tube of yellow rays shoot out from it. This tube shows us which way the light is pointing.
Ensure that the Directional Light is still selected. If you deselected it, click on the Directional Light label in the Hierarchy panel.
In the Inspector panel, change the light's position to move it up and out of the way. Enter 0 for the X position, 4 for the Y position, and -4 for the Z position. Moving a Directional Light like this does not alter its intensity, but we're just making sure it's within reach in the Scene view.
Rotate the light so that it shines down on the objects. Enter a value of 44 for the light's X Rotation in the Inspector panel.
If you're feeling adventurous, now's a great time to get a better feel for these virtual lights. Switch to the rotate mode by using the controls at the top-left of the screen, or press the E key on your keyboard. You can freely rotate the light around to see how it affects your objects.
Switch to move mode by clicking on the Move icon or by pressing W on the keyboard. Click on the Transform gizmo to move the light around the scene. How does moving the light affect the way your objects appear?
Kill the light by pressing Delete on the keyboard (Command + Delete if you're on a Mac). Add one of the other two types of lights a spotlight or a point light by clicking on GameObject | Create Other and choosing another light. You can also change an existing light's type in the Type drop-down in the Inspector panel. What's the difference between the light you chose and the directional light? Move the new light all around to get a sense of how each light type treats your objects slightly differently.
Here are the differences between the lights in a nutshell:
Directional light: This light can travel an infinite distance and illuminate everything in the Scene. This kind of light works like the sun. As we've seen, it doesn't matter how large or small a directional light is, or where you place it in the Scene only by rotating it can we determine which surfaces it illuminates.
Ambient: This is the default type of lighting that you see in your Scene, without adding any light Game Objects. Ambient lighting is the most efficient, but it's also the most boring. You can crank the level of ambient lighting in your Scene up and down by fiddling with the render settings (Edit | Render Settings). Try clicking on the Ambient Light swatch to cast a creepy, bright green glow over your entire Scene.
If this lighting stuff really revs you up, check out all of the settings and things to fiddle with within the Inspector panel when you select a light. You can get more information on what these and any other Component settings do by clicking on the blue book icon with the question mark on it in each Component section in the Inspector panel.
Unity takes care of the science behind lighting our scenes, but arranging the lights is an art. On many 3D animated movies and teevee shows, as well as on large game development teams, there's often at least one person dedicated to lighting the scene, just as there are lighting specialists on real-world film sets. Virtual lights are built to mimic the properties of real-world lights. Lighting, like modeling, can be an entirely unique discipline in the world of 3D gaming.
When you're finished exploring lights, follow the steps mentioned previously to restore your directional light, or just press Ctrl + Z or Command + Z on the keyboard to undo everything back to when you started messing around.
When you light a scene with multiple lights, it can be tricky to see which light is affecting which area. To turn a light off, select the light in the Hierarchy panel. Then, uncheck the checkbox at the top of the Inspector panel. Poof! The light is gone, but not forgotten. Check the checkbox again to make it reappear.
In fact, you can turn any GameObject on and off by using this checkbox. It's a handy way to isolate things in your Scene without deleting your hard work.
If you're working on a particularly grim game and you want to be able to see what's going on in your Scene, toggle the internal lighting by pressing the sunny little button at the top of your Scene view. When it's lit, your light Game Objects take over. When it's unlit, internal lighting hits your meshes so that you can see what's what.
If you had a good time playing with all the light settings, you're going to lose your mind when you check out the camera! Cameras in 3D programs are simulations of how the light rays bend around from a single perspective point. 3D cameras can simulate many different lenses, focal lengths, and effects. For now, we're just going to ensure that our camera is adjusted properly so that we're all on the same page, but don't be afraid to goof around with the camera controls if you're dying to get into some trouble.
In the Hierarchy panel, click to select the Main Camera Game Object. You'll notice you get a cool little Camera Preview picture-in-picture to show you what the camera "sees".
Click on the Play button to test your game.
Ack! That was anti-climactic. The Ball is just sort of sitting there, waiting to fall, and the Paddle's not moving. Somewhere in the distance, a slow, sad strain of violin music plays.
But, not to worry! We're one step away from making something amazing happen. Press the Play button again to stop testing the game.
The pitfalls of Play
Remember that when you're testing your game with the Play button activated, you can still make changes to your Scene, but these changes don't get saved! When you stop testing, everything will go back to the way it once was, like Cinderella after the royal ball. To make it very clear that you're in this potentially confusing game-testing mode, click on the Maximize on Play button at the top of the Game window. Now, whenever you test your game, the window will fill the screen to prevent you from absentmindedly messing with stuff.
I wanted you to test your game at this point, even though nothing happened, to pinpoint that magic moment when Unity becomes awesome. If you're already having a good time, you ain't seen nothin' yet!
Select the Ball in the Hierarchy panel.
In the menu, choose Component | Physics | Rigidbody.
A Rigidbody component is added to the Ball. You can see it in the list of the components of the Ball Game Object in the Inspector panel.
Click on Play to test your game.
Click on Play again when you've recovered from how awesome that was.
Unity's built-in physics engine is ready for you to hook into it, but it will ignore your Game Objects unless you opt in by adding a component like Rigidbody to your Game Object. Rigidbody is so-named to differentiate it from soft body dynamics, which are calculations that actually distort and deform your meshes. Soft bodies like cloth are partially supported in Unity 3, after numerous developers requested the feature. You can view and vote on upcoming Unity features here: http://feedback.unity3d.com/forums/15792-unity
Rigidbody dynamics treat all of our objects as if they're made of wood, steel, or very stale cake. Collider components tell Unity when Game Objects crash into each other. As both our Ball and our Paddle already have sphere and cube-shaped colliders surrounding their meshes, the missing link is the Rigidbody component. By adding a Rigidbody component to the Ball, we include the Ball in Unity's physics calculations. The result is hot ball-on-paddle action.
The Ball hits the Paddle and comes to a dead stop. Pretty cool for such a small effort, but it won't do for a keep-up game. We need to get that Ball bouncing!
Select the Ball and take a close look at its Sphere Collider component in the Inspector panel. One of the parameters, or options, is called Material. Next to that, we see the label None (Physic Material) (this text may be slightly cut off to see the whole label, click-and-drag the left edge of the Inspector panel to increase its width.) There's a small black arrow next to the label that means it's a drop-down list. What hidden wonders await us in that list?
Let's import a new package with certain goodies we'll need to make the ball bounce. In the menu, click on Assets | Import Package | Physic Materials, then click on the Import button. A bunch of Physic Materials (whatever they are) get added to our Project panel.
Make sure that the Ball is selected.
In the Inspector panel, find the Sphere Collider component of the Ball. If it is closed, click on the gray triangular arrow to expand it so that you can get at its goodies.
Find the Material parameter of the Sphere Collider.
Click on the small black circle next to the label that reads None (Physic Material).
Test your game by clicking on the Play button.
When you finally snap out of it, click on Play again to escape the mesmerizing results.
The Physic Materials package that we just imported includes a number of useful prebuilt physic materials. These special materials change what happens when a collider hits another collider. We chose the one called Bouncy, and lo and behold, when the Ball game object's Sphere Collider hits the Cube Collider of the Paddle, it reacts like a bouncy ball should. At our current phase of human technological progress, this is as close to a Make Game button as you're gonna get!
Unity's Standard Assets package provided us with a Bouncy Physic Material to use, but we could just as easily have created our own. If you want to create your own Physic Material from scratch, right-click on a blank area of the Project panel, and then select Create | Physic Material. Alternatively, you can click-and-hold the mouse button on the Create button at the top of the Project panel and choose Physic Material.
A new Physic Material called (appropriately enough) New Physic Material appears in the Project panel. You can rename it the same way you renamed the Ball and Paddle game objects. Call it BouncyBall.
Click to select the Physic Material. Its parameters are listed in the Inspector panel. If you're desperate to know what everything does, click on the blue book icon with the question mark on it, and prepare to be bored to tears by talk of anisotropic friction. YAWN! What you really want to do is change the Bouncyness to 1, and set the Bounce Combine to Maximum. Or choose your own settings if you just want to see what they do.
Select the Ball again. Find where the Sphere Collider Component's Material parameter is set to that built-in Bouncy Physic Material, and then drag-and-drop your BouncyBall Physic Material into the slot where the built-in Bouncy one is. Alternatively, you can choose your BouncyBall Physic Material from the menu. The Bouncy Physic Material is swapped for your own custom-created BouncyBall Physic Material.
What a drag!
We'll be pulling that same drag-and-drop maneuver again and again as we use Unity. If you weren't feeling up to trying those last steps, don't worry; you'll get plenty of chances to drag stuff around the interface as we build more games.
Test the game by clicking on the Play button. The paddle is flat, the ball is bouncy, and everything seems right with the world! We haven't programmed any interactivity yet, but try moving and rotating the paddle around while the game is running using the Unity tools to get a sense of how the ball might react when we rig up mouse control in the next chapter. (You'll have to deselect Maximize on Play to gain access to your tools to try this out in the Scene view.)
In this chapter, we started to put the Unity 3D engine through its paces.
We learned how to:
Add built-in Game Objects to our Scene
Position, rotate, and scale those Game Objects
Add lighting to the Scene to brighten things up
Add Rigidbody components to our Game Objects to tie into Unity's physics calculations
Create Physic Materials
Customize Collider components to make Game Objects become bouncy
We took an impossibly complex game idea and hacked it down to its fun, naked essentials. We explored the origin point the center of our game's universe. We learned about the building blocks of 3D construction: vertices, edges, and faces. We talked about how polygon counts can affect game performance. We laughed, we cried. It was profound.
What we have so far is not a game, but a very dull movie about the best keep-up player in the world who never, ever drops the ball. One key thing that distinguishes movies from games is popcorn. Also, games are interactive. We need to introduce interactivity to our game so that the player can move that paddle around.
We do this by writing a Script. Just like in the movies, where everyone follows a list of stage cues, lines, and notes to put the finished product together, Game Objects in Unity can follow Scripts to determine what to do. Scripts are essentially lists of instructions for people, or Game Objects, to follow. In the next chapter, we'll learn how to add Scripts to our Game Objects to add interactivity to our game.