Sunday, February 3, 2013

Translate that for me, will you?

To move an object, specifically the player, you have to translate that object along the X, Y and Z axis. The three basic steps in calculating the translation value are:

  1. Obtain the input value range
  2. Multiply by the desired speed
  3. Multiply by delta time (to allow the object to move based on time and not computer speed)

In Unity, there are several ways to obtain the input value range of the player. You could poll for keyboard or other input events and translate the object along the particular axis that corresponds with the key pressed. For example, in a 2D game where the origin is in the bottom left of the screen (positive Y moves up the screen, positive X moves to the right of the screen),

float playerSpeed = 10.0f;
if (Input.GetKey(KeyCode.W))
{
transform.Translate(playerSpeed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(-playerSpeed * Time.deltaTime, 0, 0);
}

// etc...

This is a very verbose method of getting the player input and translating the player object. A better, more preferred method is to use GetAxis.

float playerSpeed = 10.0f;

float xTranslation = Input.GetAxis(“Horizontal”) * playerSpeed * Time.deltaTime;
float yTranslation = Input.GetAxis(“Vertical”) * playerSpeed * Time.deltaTime;

transform.Translate(xTranslation, yTranslation, 0);


This is a much more concise method. Through Input.GetAxis, we pass in the name of the virtual axis, as setup in the Input Manager, and get returned the input value range (-1 to 1). Horizontal and Vertical are default input settings, which make use of WASD, arrows, and a gamepad left analog joystick.

If the player is holding down the ‘D’ key, Input.GetAxis(“Horizontal”) will return a value of 1. If the player is holding down the ‘S’ key, Input.GetAxis(“Horizontal”) will return a value of -1. Multiplying that by playerSpeed will cause the player game object to move along the X axis in a positive direction by 10 units. Further multiplying this by Time.deltaTime allows us to move independent of the computer speed, so we get same rate of movement regardless of how fast the player’s machine may be.

No comments:

Post a Comment