Game Development Reference
In-Depth Information
Developing the player controls code
The third system we need to implement is the controls or how the character will re-
spond to the user input. As a first pass, we need to be able to move our player in
the world, so we will implement walk forward, walk backwards, walk left, and walk
right. Luckily for us, Unity gives us an input system with axes so that we can write
our control code once, and it will work with any devices that have an axis (such as
keyboard or joypad). Of course, the devil is in the detail and keyboard controls be-
have differently from joypads, so we will write our code for keyboard input as it is the
most responsive and most ubiquitous device. Once this script is finished, its behavior
in combination with the GameCam script will control how the player motion feels in the
game.
Implementing PlayerControls.cs
For every frame our player updates, perform the following steps that describe our
PlayeControls algorithm:
1. Store the forward and right vectors of the current camera.
2. Store the raw axis input from the controller (keyboard or joystick). These val-
ues will range from -1.0 to 1.0 , corresponding to full left or right, or full for-
ward or backwards. Note that if you use a joystick, the rate of change of these
values will generally be much slower than if a keyboard is used, so the code
that processes it must be adjusted accordingly.
3. Apply the raw input to transform the current camera basis vectors and com-
pute a camera relative target direction vector.
4. Interpolate the current movement vector towards the target vector and damp
the rate of change of the movement vector, storing the result away.
5. Compute the displacement of the camera with movement * movespeed and
apply this to the camera.
6. Rotate the camera to the current move direction vector.
Now let's implement this algorithm in C# code:
1. Right click on the Chapter1 assets folder and select Create New C#
Script . Name it PlayerControls.cs . Add this script to GameObject of
Player1 by dragging-and-dropping it onto the object.
Search WWH ::




Custom Search