From the player input to a new position in the world

Every time the player presses a key on the keyboard, or use the thumbstick on a controller, we need to retrieve this input. Then, we need to elaborate it so that we can calculate the next position of our character after a frame.

Since it's a calculation we need to do for every frame, it's reasonable to do it in the Update() function. However, since we are going to use physics, we need to use a similar function, called FixedUpdate(). So, let's rename Update to FixedUpdate(), as the following:

void FixedUpdate () {

}

To retrieve the player input, we can use the default key mapping in Unity.

In case you would like to change this mapping, you can do it by clicking the top bar and then Edit | Project Settings | Input.

In particular, we can use the Input.GetAxis() function, and using as a parameter a string with the name of the axis. In our case, we have the Horizontal and the Vertical axis. These are values that range from -1 to 1 depending on how tilted the thumbstick is (or, in the case of a keyboard, they can just be -1, 0, and 1). Thus, we need to multiply these values by the speed variable, and then multiply it by the Time.deltaTime, which is the time since the last frame. Finally, we need to add the current position of the character with transform.position and the corresponding axis. It sounds complicated, but it's not once the code is written down. For those of you who are familiar with equations, this is what we will be using:

So, finally here is the code, in which we do the same operation once for the x-axis and again for the y-axis, and store values within variables:

  void FixedUpdate () {
//Get the new position of our character
var x = transform.position.x + Input.GetAxis("Horizontal") * Time.deltaTime * speed;
var y = transform.position.y + Input.GetAxis("Vertical") * Time.deltaTime * speed;
}
..................Content has been hidden....................

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