User Inputs :: GameDev Unity3D cookbook

User Inputs are the commands users use to control characters in a game. So, user inputs play a main role in any game development.

User Input ::
You should create a new JavaScript in your Project panel, and name it BasicInputHandler, and insert the following code:
[code lang=”Javascript”]
function Update () {
//Move object through Z axis
if(Input.GetAxis(“Vertical”) > 0){
transform.Translate(Vector3.forward * Time.deltaTime);
}
else if(Input.GetAxis(“Vertical”) < 0){
transform.Translate(- Vector3.forward * Time.deltaTime);
}

//Move object through X axis
if(Input.GetKey("d")){
transform.Translate(Vector3.right * Time.deltaTime);
}
else if(Input.GetKey("a")){
transform.Translate(- Vector3.right * Time.deltaTime);
}
}
[/code]
Add a cube in your scene, drag and drop, the BasicInputHandler script to this cube.

This script check the user input in two ways: through the Vertical axis in Input object, and if keys were pressed.

Veja o exemplo aqui.

Axis option ::
In Unity3D, there is this Input global object, that captures any user input, and make this information available to all other game objects. This Input object has some default settings, like Vertical and Horizontal axis. The Vertical axis is activated by W, S, up-arrow, and down-arrow.
THOSE SETTINGS CAN BE MODIFIED at EDIT >> Project Settings >> Input menus. The Inspector panel will show the axis configurations in the Input object, and you can modify them as you wish.

Keys option
You can also use the GetKey function to capture user inputs. The Input object, captures when keys a pressed, and this information is available to you.

Both ways are valid, and easy to use, but they slightly differ in the results.
Check the sample, and pay attention the at the difference between the controls W/S, and A/D, when you release the keys.

Leave a Reply

Your email address will not be published. Required fields are marked *