© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
M. KillickThe Way We Playhttps://doi.org/10.1007/978-1-4842-8789-7_4

4. First-Person Character Controller in Unity

Michael Killick1  
(1)
Cambridge, UK
 

For this chapter, you will now be shown how you can create a first-person controller within Unity which can be used as the foundation for a future project or your first game.

Set Up

Before we can begin to create our project, we will need to install Unity and create a blank project. You will need to download Unity Hub which is the home for all updates, your projects, and installations of Unity. You can find this download from the Unity website.

Once downloaded and installed, you will need to create a free Unity account to start making projects. This will also allow you to sync any projects if you log in to a different machine in the future. It will also provide you with a free license to create games on your machine. If you ever create any games commercially, then you will need a professional license, which you can purchase through Unity. Once set up, you will need to click the Install Editor button and select the version of Unity you would like to use. You can see this in Figure 4-1. I would recommend using the version that is recommended by Unity as this will be the most stable and up-to-date version at the time.

A screenshot of the Install Unity Editor frame focuses on the official release options available for installation. The topmost version, the recommended version, is 2021.3.81 L T S.

Figure 4-1

Unity Hub and Unity software versions

2021.3.8f is my recommended version to use, but do ensure that you select which one has been recommended by Unity to use for this tutorial. Once chosen, you will need to select some modules which will support Unity. As I am running a Mac, in the tutorial, you can see that it has been selected for me to have Visual Studio installed as well. This might not appear for you if you have already got Visual Studio installed on your machine. If you decide to use another code editor, then you can untick Visual Studio to be added. You will need to scroll through the list and choose either Mac Build Support or Windows Build Support, depending on the machine you are using. You are now ready to begin the install!

Once the software has been installed, you can now create a new project. Click the blue button which says New Project. On the left-hand side, choose Core. Then select 3D and give the project a name, such as “FSP Test Build.” You can see this in Figure 4-2. When you are ready, click Create Project and wait for Unity to open!

A screenshot of the New Project window in the Unity Editor with a new project named F P S Test Build with a 3 D core type project setup.

Figure 4-2

Unity Hub with the selection of templates

Step 1

Create an Empty Object as shown in Figure 4-3 and then name this “First Person Player.” Then put this somewhere in the center of the scene.

A screenshot of the Hierarchy tab with the mouse pointer focused on the Create Empty menu.

Figure 4-3

Unity Hierarchy and creation of assets

Step 2

Under the First Person Player object, click the Add Component button under the Inspector. Then choose the character controller . Click Gizmos at the top right of the scene so you can then see the character controller in the scene, as depicted in Figure 4-4.

A screenshot of a scene within the Unity Editor depicts a tiled floor and wall setup with the x, y, and z axes marked on a wall at the far end.

Figure 4-4

Scene view with character controller

Step 3

Set the values of the character controller to the following. This will allow the player to take the form of a normal size human . This can be seen in Figure 4-5.

A screenshot of the inspector menu with values filled in for the transform and character controller submenus. The transform menu has 3 boxes corresponding to the 3 axes for position, rotation, and scale. The character controller submenu has boxes for the following fields, slope limit, step offset, skin width, min move distance, center, radius, and height.

Figure 4-5

First Person Player in the Inspector

Radius = 0.6

Height = 3.8

Step 4

We now want to add some graphics to the player to make it feel more realistic. Go ahead and right-click the First Person Player object in the Hierarchy and add a 3D Object – Cylinder . This will generate an object that will act as your player, which has been depicted in Figure 4-6.

A screenshot of the Sample Scene menu with the mouse hovering atop the Cylinder option within the 3 D object sub-menu.

Figure 4-6

Unity Hierarchy showing Cylinder object creation

Step 5

Be sure to then set the Scale to the following so this matches the same size as your First Person Player object. You also need to remove the Capsule Collider as we will be making our own collisions later in the lesson. You can do so by clicking the cog on the far right of the component or by right-clicking the Capsule Collider component and clicking “Remove Component.” You can see this in Figure 4-7.

Scale:

X = 1.2

Y = 1.8

Z = 1.2

A screenshot of the Inspector menu with values filled in for the sub-menus. The mouse pointer hovers over the Remove Component sub-menu.

Figure 4-7

Cylinder in the Inspector and removing the Capsule Collider component

Step 6

The next step is to attach a camera to the player so we can see the game from a first-person perspective. Drag the main camera in the scene onto your Player object. You then need to reset the transform position from the Transform option on the Inspector. You also need to drag the camera in the scene to where the head would be on your player, so the camera is eye level. Have a look at Figure 4-8.

A screenshot of the hierarchy tab in which the mouse pointer hovers over the main camera submenu. The corresponding main camera window is below.

Figure 4-8

Dragging the camera to make it a child of the First Person Player

Step 7

We now need to set up the script which will allow the player to look around. This will work using the X and Y axes and will be locked so they can only look around a certain amount. This is called clamping .

Under the Inspector of your camera, click Add Component and start to type MouseLook . This will create a new C# script with that name. Once created, double-click the script which will then open your default code editor. When ready, you will need to add in the following programming:
public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public Transform playerBody;
    float xRotation = 0f;
    void Start()
    {x
       Cursor.lockState = CursorLockMode.Locked;
    }
    void Update ()
    {
       float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
       float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
       xRotation -= mouseY;
       xRotation = Mathf.Clamp(xRotation, -90f, 90f);
       transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
       playerBody.Rotate(Vector3.up * mouseX);
    }
}

When writing the script, it is handy to know a few things about it. We have begun by setting up some variables which will hold values for our camera, such as mouseSensitivity, which will allow you to change how sensitive the mouse will be when aiming. During our Start Event (void Start), we are locking the cursor , which means that this will not appear in the game while testing/playing. (When running the game and you wish for your cursor to reappear, press Escape on your keyboard.) mouseX and mouseY are both inputs that are built into Unity’s library, which have already been given a button or a gesture. These have been set up to work with the mouse if it were to move up or down, which, in turn, will allow the player to look up and down. And Mathf.Clamp(xRotation, -90f, 90f) is locking how far the player can look up and down. No person can roll their head backward to see behind them, so why should your character do that too?

If completed correctly, you should now have a working script that allows the player to look around the world. Make sure that you test this just to be sure that everything has worked!

Step 8

Now go to your Player object and create a new script called PlayerMovement . The difference is with this script, we no longer need a void Start Event. Be sure to delete this so the void Update remains. When ready, open this script in your code editor and add in the following programming into the new script:
public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    Vector3 velocity;
    void Update()
    {
       float x = Input.GetAxis("Horizontal");
       float z = Input.GetAxis("Vertical");
       Vector3 move = transform.right * x + transform.forward * z;
       controller.Move(move * speed * Time.deltaTime);
       velocity.y += gravity * Time.deltaTime;
       controller.Move(velocity * Time.deltaTime;
    }
}

Just as before, here is a little recap of some of the things we have written about in the script. The CharacterController refers to the component we attached to the Player object at the start of this tutorial and will interact with our code to create movement for our character . The public floats for speed and gravity are default values which can be changed later depending on your game idea. With these variables being made “public,” it allows you to edit these values within the Inspector without the need of opening the movement script if you need to make any changes or adjustments.

Floats X and Z refer to moving the player forward and the direction the player is looking. Just like Mouse X and Mouse Y, these functions are built into Unity’s library and are binded to the arrow keys and WASD. And our Vector3 move = transform.right * x + transform.forward * z refers to our functions multiplying by each other to create movement. Imagine only one of the character’s legs working, neither can work without the other!

If completed correctly, you should now have a working movement script. However, in order for us to test our movement script, we will need a surface that our character can move across. Refer to Figure 4-9. To create a simple ground object, right-click in the Hierarchy and move down to 3D Object and choose Plane. Name this Environment. This will create a 2D surface that your player will be able to move around on. Make sure that you align this surface with the base of your character so it is standing on it.

A screenshot of the Hierarchy tab with the mouse pointer hovering over the Plane sub-menu within the 3 D object menu.

Figure 4-9

Creating a Plane from the Hierarchy

Step 9

We now want to make a Ground Check object which will allow the player to interact with the ground if the player jumps. This will act as precise collision checking and ensure that your player is interacting with the ground beneath them. There are different methods to create this and to avoid this situation from happening, but this is a simple method that is not just used in Unity for 3D games but can also be used when creating 2D games. Right-click the player in the Hierarchy and create an Empty Game Object. This object then needs to be dragged to the bottom of the Player object in the scene. You also need to rename this to Ground Check under the Inspector. You can see this in Figure 4-10.

A screenshot of the Hierarchy tab with the mouse pointer hovering on top of the Create Empty sub-menu within the First Person Player menu.

Figure 4-10

Unity Hierarchy showing creating an empty object for Ground Check

Step 10

Now return to the movement script and insert this new programming so collisions can now be applied to the Ground Check. You can see the new additions to the script which are highlighted in bold :
public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    public Transform groundCheck;
    public float groundDistance = 0.4;
    public LayerMask groundMask;
    Vector3 velocity;
    bool isGrounded;
    void Update()
    {
       isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
       if(isGrounded && velocity.y < 0)
       {
           velocity.y = -2fp;
       }
       float x = Input.GetAxis("Horizontal");
       float z = Input.GetAxis("Vertical");
       Vector3 move = transform.right * x + transform.forward * z;
       controller.Move(move * speed * Time.deltaTime);
       velocity.y += gravity * Time.deltaTime;
       controller.Move(velocity * Time.deltaTime;
    }
}
To complete this step, click and drag the Ground Check object from the Hierarchy to the Inspector under the Ground Check float. Refer to Figure 4-11.

A screenshot of the Player Movement Script menu with values filled in for various fields to facilitate adding a component.

Figure 4-11

First Person Player in the Inspector and applying the Ground Check object

Step 11

We now need to set up the layer for the ground that the player will be able to interact with when jumping. To create a new layer, go to the layer option on the right-hand side and choose Add Layer. Refer to Figure 4-12.

A screenshot of the First Person Player menu within the Inspector window. The mouse pointer hovers over the Add Layer submenu within the layer dropdown window menus.

Figure 4-12

First Person Player in the Inspector to change the Layer type

Then create a new layer called Ground in a black Builtin Layer box. You can see this in Figure 4-13.

A screenshot of the Inspector's Tags and Layers window has values filled in for layers 1 to 7. Layer 8 is the Player and layer 9 is the Ground.

Figure 4-13

Layer settings in the Inspector to create a new Ground layer

Return to the Player object, and then in the Inspector, under the option of Ground Mask, choose the new Ground layer you created. This is shown in Figure 4-14.

A screenshot of the Player Movement Script menu with values filled in. The mouse pointer hovers over the Ground submenu within the Ground Mask dropdown menu.

Figure 4-14

First Person Player Inspector and applying the Ground layer to the PlayerMovement script

To be sure that your environment is interactable, you will need to click your environment object or the object that your player walks upon and change the layer to Ground. Take a look at Figure 4-15.

A screenshot of the Inspector menu with values filled in for the Transform menu. The mouse pointer hovers over the Ground submenu within the Default layer's dropdown menu.

Figure 4-15

Environment in the Inspector and applying the Ground layer

Step 12

To complete this tutorial, we will now add the ability to jump into our game. To do this, return to your PlayerMovement script again and add in the following code which has been highlighted in bold:
public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;
    public Transform groundCheck;
    public float groundDistance = 0.4;
    public LayerMask groundMask;
    Vector3 velocity;
    bool isGrounded;
    void Update()
    {
       isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
       if(isGrounded && velocity.y < 0)
       {
          velocity.y = -2fp;
       }
       float x = Input.GetAxis("Horizontal");
       float z = Input.GetAxis("Vertical");
       Vector3 move = transform.right * x + transform.forward * z;
       controller.Move(move * speed * Time.deltaTime);
       if(Input.GetButtonDown("Jump") && isGrounded)
       {
          velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
       }
       velocity.y += gravity * Time.deltaTime;
       controller.Move(velocity * Time.deltaTime;
    }
}

You can now run your game! This should mean that you now have a fully working first-person controller which can be the start of a new FPS game!

Bonus Stage: Common Unity Terms

As a bonus, Table 4-1 lists some common Unity terms that are used when working within the engine. If you decide to develop your skills further within this engine, these terms will be useful!
Table 4-1

Common Unity Terms

Asset Store

A Unity website that lets you download premade assets for use in your game development projects. Unity developers can also publish their own premade assets to the Asset Store for other developers to download and use.

Bool

A Boolean is a variable which can go two ways, on or off. This can be used to define a situation which is seen as True or False.

Camera

Orthographic camera

A camera view that makes objects appear fixed on the screen, regardless of their actual distance from one another or their relative positions. This is commonly used for retro-style 2D games, as it can make GameObjects look flat, or 2.5D games (2D games that utilize 3D elements), specifically because they allow for touches of 3D depth and definition while maintaining an otherwise 2D appearance.

Perspective camera

A camera view that projects objects according to their actual placement and distance on screen, giving viewers a sense of their real-world positions. This is commonly used for fully 3D titles.

Component

Something that is attached to a GameObject to alter its functionality.

Editor

The dashboard on which all of Unity’s functionality is made available to its users.

Entity

A GameObject that receives components for functionality.

Public float

A variable that contains a numeric value stored in a floating point. This can be changed within the Inspector of Unity.

Private float

A variable that contains a numeric value stored in a floating point. This can only be changed within the script it was created in.

GameObject

Characters, props, and scenery in Unity.

Hierarchy window

A window in the Unity Editor that displays all GameObjects currently being used in your Scene.

Inspector window

The window in which you can view and edit the properties and settings of almost everything that appears in the Unity Editor, including assets, GameObjects, and the Editor itself.

Instance

A specific version of a GameObject created from a template and modified to carry specific traits and behaviors that differentiate it from its original form.

Instantiation

The creation of an instance.

Materials

Editor objects that store the properties of surfaces in Unity , such as texture, shader, and color tint settings.

Package

A container that holds any combination of Assets, Shaders, Textures, plug-ins, icons, and scripts that enhance various parts of your project.

Package Manager

A feature within the Unity Editor that allows you to download and install add-ons and enhancements (packages) for the Unity Editor.

Prefab

A typically customized, reusable version of a GameObject.

ProBuilder

A Unity feature that enables designers to build, edit, and texture custom 3D geometry for in-scene level design.

Project window

Effectively the file finder in Unity. This is where you will be able to dive into your Scene, Asset, Prefab, and other folders.

Rigidbody

A component in Unity that lends a GameObject the ability to react to its environment through physics, for instance, giving a GameObject mass.

Runtime

The rendered, platform-specific output (e.g., for iOS, Android, Oculus, or PlayStation 4) from a Unity project .

Scene

The entire editable area in which a game can be built. Environments, props, obstacles, NPCs, menu functions, and more can be a part of each Scene in Unity.

Shader Graph

A visual Shader editing tool in Unity that lets developers create Shaders without having to write code.

Timeline

A feature in Unity for creating cinematic content, gameplay sequences, audio sequences, and complex particle effects.

Time.DeltaTime

This property provides the time between the current and the previous frame.

UI Elements

A unified UI editing tool in Unity. As of Unity 2020.1, this is known as the UI Toolkit.

Vector3

Creates a new vector with given x, y, z components.

Visual Effect Graph

A node-based visual effect editor that lets developers author visual effects that Unity simulates directly on the GPU.

Conclusion

So far within this chapter, we have covered the following:
  1. 1.

    How to use Unity

     
  2. 2.

    How do you program your character?

     
  3. 3.

    Setting up a camera to view your world

     

With Chapter 4 now completed, we will now begin to look at the designing of your world and a favorite topic of mine, level design. This will look into the fundamentals of “fun” and how to be creative with the levels you intend to make. To help prepare yourself for this chapter, start to think about some games you have played and thought they either had excellent looking graphics or were cleverly designed to suit the story and the gameplay. We will be thinking about a lot of games during this next chapter!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset