Unity supports keyboard, joystick and gamepad input.
Virtual axes and buttons can be created in the Input Manager, and end users can configure Keyboard input in a nice screen configuration dialog.
You can setup joysticks, gamepads, keyboard, and mouse, then access them all through one simple scripting interface.
From scripts, all virtual axes are accessed by their name.
Every project has the following default input axes when it's created:
If you want to add new virtual axes go to the
menu. Here you can also change the settings of each axis.You map each axis to two buttons on a joystick, mouse, or keyboard keys.
Name | The name of the string used to check this axis from a script. |
Descriptive Name | Positive value name displayed in the input tab of the | dialog for standalone builds.
Descriptive Negative Name | Negative value name displayed in the Input tab of the | dialog for standalone builds.
Negative Button | The button used to push the axis in the negative direction. |
Positive Button | The button used to push the axis in the positive direction. |
Alt Negative Button | Alternative button used to push the axis in the negative direction. |
Alt Positive Button | Alternative button used to push the axis in the positive direction. |
Gravity | Speed in units per second that the axis falls toward neutral when no buttons are pressed. |
Dead | Size of the analog dead zone. All analog device values within this range result map to neutral. |
Sensitivity | Speed in units per second that the the axis will move toward the target value. This is for digital devices only. |
Snap | If enabled, the axis value will reset to zero when pressing a button of the opposite direction. |
Invert | If enabled, the Negative Buttons provide a positive value, and vice-versa. |
Type | The type of inputs that will control this axis. |
Axis | The axis of a connected device that will control this axis. |
Joy Num | The connected Joystick that will control this axis. |
Use these settings to fine tune the look and feel of input. They are all documented with tooltips in the Editor as well.
You can query the current state from a script like this:
value = Input.GetAxis ("Horizontal");
An axis has a value between -1 and 1. The neutral position is 0. This is the case for joystick input and keyboard input.
However, Mouse Delta and Window Shake Delta are how much the mouse or window moved during the last frame. This means it can be larger than 1 or smaller than -1 when the user moves the mouse quickly.
It is possible to create multiple axes with the same name. When getting the input axis, the axis with the largest absolute value will be returned. This makes it possible to assign more than one input device to one axis name. For example, create one axis for keyboard input and one axis for joystick input with the same name. If the user is using the joystick, input will come from the joystick, otherwise input will come from the keyboard. This way you don't have to consider where the input comes from when writing scripts.
To map a key to an axis, you have to enter the key's name in the Positive Button or Negative Button property in the Inspector.
The names of keys follow this convention:
The names used to identify the keys are the same in the scripting interface and the Inspector.
value = Input.GetKey ("a");
On iOS and Android, the Input class offers access to touchscreen, accelerometer and geographical/location input.
Access to keyboard on mobile devices is provided via the iOS keyboard.
The iPhone and iPod Touch devices are capable of tracking up to five fingers touching the screen simultaneously. You can retrieve the status of each finger touching the screen during the last frame by accessing the Input.touches property array.
Android devices don't have a unified limit on how many fingers they track. Instead, it varies from device to device and can be anything from two-touch on older devices to five fingers on some newer devices.
Each finger touch is represented by an Input.Touch data structure:
fingerId | The unique index for a touch. |
position | The screen position of the touch. |
deltaPosition | The screen position change since the last frame. |
deltaTime | Amount of time that has passed since the last state change. |
tapCount | The iPhone/iPad screen is able to distinguish quick finger taps by the user. This counter will let you know how many times the user has tapped the screen without moving a finger to the sides. Android devices do not count number of taps, this field is always 1. |
phase | Describes so called "phase" or the state of the touch. It can help you determine if the touch just began, if user moved the finger or if he just lifted the finger. |
Phase can be one of the following:
Began | A finger just touched the screen. |
Moved | A finger moved on the screen. |
Stationary | A finger is touching the screen but hasn't moved since the last frame. |
Ended | A finger was lifted from the screen. This is the final phase of a touch. |
Canceled | The system cancelled tracking for the touch, as when (for example) the user puts the device to her face or more than five touches happened simultaneously. This is the final phase of a touch. |
Following is an example script which will shoot a ray whenever the user taps on the screen:
var particle : GameObject; function Update () { for (var touch : Touch in Input.touches) { if (touch.phase == TouchPhase.Began) { // Construct a ray from the current touch coordinates var ray = Camera.main.ScreenPointToRay (touch.position); if (Physics.Raycast (ray)) { // Create a particle if hit Instantiate (particle, transform.position, transform.rotation); } } } }
On top of native touch support Unity iOS/Android provides a mouse simulation. You can use mouse functionality from the standard Input class.
As the mobile device moves, a built-in accelerometer reports linear acceleration changes along the three primary axes in three-dimensional space. Acceleration along each axis is reported directly by the hardware as G-force values. A value of 1.0 represents a load of about +1g along a given axis while a value of -1.0 represents -1g. If you hold the device upright (with the home button at the bottom) in front of you, the X axis is positive along the right, the Y axis is positive directly up, and the Z axis is positive pointing toward you.
You can retrieve the accelerometer value by accessing the Input.acceleration property.
The following is an example script which will move an object using the accelerometer:
var speed = 10.0; function Update () { var dir : Vector3 = Vector3.zero; // we assume that the device is held parallel to the ground // and the Home button is in the right hand // remap the device acceleration axis to game coordinates: // 1) XY plane of the device is mapped onto XZ plane // 2) rotated 90 degrees around Y axis dir.x = -Input.acceleration.y; dir.z = Input.acceleration.x; // clamp acceleration vector to the unit sphere if (dir.sqrMagnitude > 1) dir.Normalize(); // Make it move 10 meters per second instead of 10 meters per frame... dir *= Time.deltaTime; // Move object transform.Translate (dir * speed); }
Accelerometer readings can be jerky and noisy. Applying low-pass filtering on the signal allows you to smooth it and get rid of high frequency noise.
The following script shows you how to apply low-pass filtering to accelerometer readings:
var AccelerometerUpdateInterval : float = 1.0 / 60.0; var LowPassKernelWidthInSeconds : float = 1.0; private var LowPassFilterFactor : float = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; // tweakable private var lowPassValue : Vector3 = Vector3.zero; function Start () { lowPassValue = Input.acceleration; } function LowPassFilterAccelerometer() : Vector3 { lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor); return lowPassValue; }
The greater the value of LowPassKernelWidthInSeconds
, the slower the filtered value will converge towards the current input sample (and vice versa).
Reading the Input.acceleration variable does not equal sampling the hardware. Put simply, Unity samples the hardware at a frequency of 60Hz and stores the result into the variable. In reality, things are a little bit more complicated -- accelerometer sampling doesn't occur at consistent time intervals, if under significant CPU loads. As a result, the system might report 2 samples during one frame, then 1 sample during the next frame.
You can access all measurements executed by accelerometer during the frame. The following code will illustrate a simple average of all the accelerometer events that were collected within the last frame:
var period : float = 0.0; var acc : Vector3 = Vector3.zero; for (var evnt : iPhoneAccelerationEvent in iPhoneInput.accelerationEvents) { acc += evnt.acceleration * evnt.deltaTime; period += evnt.deltaTime; } if (period > 0) acc *= 1.0/period; return acc;
The Unity mobile input API is originally based on Apple's API. It may help to learn more about the native API to better understand Unity's Input API. You can find the Apple input API documentation here:
Note: The above links reference your locally installed iPhone SDK Reference Documentation and will contain native ObjectiveC code. It is not necessary to understand these documents for using Unity on mobile devices, but may be helpful to some!
Device geographical location can be obtained via the iPhoneInput.lastLocation property. Before calling this property you should start location service updates using iPhoneSettings.StartLocationServiceUpdates() and check the service status via iPhoneSettings.locationServiceStatus. See the scripting reference for details.
Page last updated: 2013-04-26