Digging into Unity3D – Part 2

So yesterday I spent several hours with Unity and discovered some cool stuff.

First I put together something like a Hello World app… certainly not a game, but what I’d consider the bare minimum that’s still “something”. I wouldn’t quite call this a tutorial since I only started myself, but if you are at Step Zero with Unity you may find it useful in understanding the basics.  At the end, we’ll have a terrain, a sky, and a controllable player. There will be a camera tied to the capsule in first person. Then once we’ve done that, we’ll switch it to third person. Most of these instructions were found in the comments of the scripts that come with Unity… which was the first revelation that I had about how to learn. Online tutorials are good, but the example stuff is commented very well and explains a lot.

So, here’s what I did.

  1. Make a new project and use the standard Unity assets.
  2. Let’s rearrange our windows a bit so we can see the game and scene views at the same time. Drag the Scene tab down to the bottom of the Scene viewport. It should expand to fill the bottom half. Release it and you’ll have the Game view on top and the Scene view on the bottom. Very handy.
  3. Choose Menu->Terrain->Create Terrain
  4. Choose Menu->GameObject->Create Other->Directional Light
  5. With the directional light selected, hit “E” to enter rotate mode.
  6. Grab the red circle on the rotation maniuplator and drag it until it’s about 45 degrees down (+45 degrees if you’re looking at the transform in the Inspector to the right.) Notice the terrain lighting up.
  7. Choose Main Camera in the Hierarchy Panel
  8. Choose Menu->Component->Rendering->Skybox – This creates a spot for us to drop a piece of Skybox art onto the camera. Once we do, it knows exactly how to act.
  9. In the Project Panel, there are some basic starter assets. Get to Standard Assets->Skyboxes and drag Blue Sky over to Inspector panel with the Main Camera still selected. Drop it on the spot that says Custom Skybox.  The sky should show up in the Game view, but not the Scene view.
  10. Now we’ve got land and a sky. Let’s add a player. Choose Menu->GameObject->Create Other->Capsule.
  11. Click in the Scene view and then make sure Capsule is still selected. Hit “F” to focus on the capsule. Pretty cool how it smoothly zooms for you so you can get some idea of relational space.
  12. The capsule is half in the terrain, so let’s raise it up. Hit “W” to go into Move mode and drag the Green arrow up a bit. Hit F again to refocus.
  13. Now here’s interesting part. In Project, open up the Camera Scripts folder. Double click on MouseLook. Notice in the comments that there’s instructions on how to make the Capsule into an FPS style character. They read:
?View Code CSHARP
using UnityEngine;
using System.Collections;
 
/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation
 
/// To make an FPS style character:
/// - Create a capsule.
/// - Add a rigid body to the capsule
/// - Add the MouseLook script to the capsule.
///   -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSWalker script to the capsule
 
/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
///   -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {
 
	public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
	public RotationAxes axes = RotationAxes.MouseXAndY;
	public float sensitivityX = 15F;
	public float sensitivityY = 15F;
 
	public float minimumX = -360F;
	public float maximumX = 360F;
 
	public float minimumY = -60F;
	public float maximumY = 60F;
 
	float rotationX = 0F;
	float rotationY = 0F;
 
	Quaternion originalRotation;
 
	void Update ()
	{
		if (axes == RotationAxes.MouseXAndY)
		{
			// Read the mouse input axis
			rotationX += Input.GetAxis("Mouse X") * sensitivityX;
			rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
 
			rotationX = ClampAngle (rotationX, minimumX, maximumX);
			rotationY = ClampAngle (rotationY, minimumY, maximumY);
 
			Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
			Quaternion yQuaternion = Quaternion.AngleAxis (rotationY, Vector3.left);
 
			transform.localRotation = originalRotation * xQuaternion * yQuaternion;
		}
		else if (axes == RotationAxes.MouseX)
		{
			rotationX += Input.GetAxis("Mouse X") * sensitivityX;
			rotationX = ClampAngle (rotationX, minimumX, maximumX);
 
			Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
			transform.localRotation = originalRotation * xQuaternion;
		}
		else
		{
			rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
			rotationY = ClampAngle (rotationY, minimumY, maximumY);
 
			Quaternion yQuaternion = Quaternion.AngleAxis (rotationY, Vector3.left);
			transform.localRotation = originalRotation * yQuaternion;
		}
	}
 
	void Start ()
	{
		// Make the rigid body not change rotation
		if (rigidbody)
			rigidbody.freezeRotation = true;
		originalRotation = transform.localRotation;
	}
 
	public static float ClampAngle (float angle, float min, float max)
	{
		if (angle < -360F) 			angle += 360F; 		if (angle > 360F)
			angle -= 360F;
		return Mathf.Clamp (angle, min, max);
	}
}

Now, there are a few little things in those comments that might be confusing to an absolute beginner.


///To make an FPS style character:
/// - Create a capsule.

We’re good here.

/// - Add a rigid body to the capsule
With the Capsule selected, choose Menu->Component->Rigid Body

/// - Add the MouseLook script to the capsule.
Drag the MouseLook script from the Project panel onto the Capsule’s empty area in the Inspector

/// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
Set the “Axes” to “MouseX”

/// - Add FPSWalker script to the capsule
Drag this to the Capsule’s Inspector from Project panel->Standard Assets->Scripts

Once you do all this stuff, hit the play button up top. If you’ve done it right, the the ASWD keys will move your capsule around and your mouse will turn it in the Scene view. Sweet, right?

The next steps actually hook a camera up to the Capsule. Unity relies on object hierarchies much like 3D modeling software does. So if I were in 3DSMax and I wanted to have a camera attached to this capsule, I’d parent the camera to the capsule… and that’s exactly what we do here.

So, in the Hierarchy panel, drag the Main Camera onto the Capsule. Now again, just like in 3D software, the transform of the camera is now relative to the capsule instead of the world. So let’s put the Camera at 0,0,0 in the Capsule’s space by selecting the camera, clicking the little Gear icon next to its Transform in the Inspector panel, and choosing “Reset”. Notice that X,Y,Z all go back to 0? You may also notice the Game view updating a bit. Hard to tell since the Terrain is completely flat. In fact, let’s paint some test terrain real quick to have a frame of reference.

Choose the Terrain in the Hierarchy panel. Notice in the inspector there is a series of icons for painting terrain? Just get in there and mess it up a bit. We just need a few hills and valleys to be able to tell what’s going on. Click in the Scene view and either mousewheel to zoom out or hit F to expand the view. Then click the Raise Terrain button on the Terrain inspector and paint some hills. Try not to paint exactly on the Capsule since it will put the Capsule below the Terrain. Just do some stuff off in the distance so we can tell what’s going on.

Now let’s run the game and see what we see. Nice! If you click in the game view, you’ll see that the mouse now turns the camera and ASWD moves, all in first person.

The last step is to make it so the camera can look up and down. Going back to the script’s comments,


/// - Add a MouseLook script to the camera.
/// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)

So let’s do just that. With the Main Camera selected, drag that MouseLook script over and set the Axes to MouseY. Hey, we can look up and down. Nice.

Ok so lastly, you need to be introduced as early as possible to one of the big gotchas in Unity 2.5. Notice that the game is still running? Click the Play button while looking at the Inspector panel with the Main Camera selected.

Hey! Our MouseLook disappeared! WTF? Yes, ANYTHING you do while the game is running is considered an “experiment” and is NOT saved. You could work for hours and lose all of it. So get in the habit VERY early of knowing when you are and are not playing the game. Got it? :)



4 Thoughts

  1. For readers having problems distinguishing between when Unity is playing and when it isn’t (relating to the last “gotcha” in this post), a good idea might be to choose a darker or more intense color for the playmode tint in preferences under color settings. Unity automatically uses this coor to tint everything but the Game view when things are playing.

  2. Ben says:

    @Charles – good point.

    Question though… Is the transient nature of live-game edits a design decision or a technical limitation in Unity?

  3. col000r says:

    One thing you can do though to save changes you’ve made in play mode is to select the affected GameObject in the inspector and Copy it, then stop the game and paste it back in. Voilà – changes saved!

  4. Ben says:

    I tried the playmode tint Charles suggested and that is a really good way to help with this issue. Thanks Charles.

Your Thoughts...


All content © Copyright 2012 by Ben Throop.
Subscribe to RSS Feed – Posts or just Comments

Powered by WordPress
Based on a Theme by Graph Paper Press