Handling Inputs In Unity
Nov 8, 2020
Inputs in Unity allows the user to control the game using devices like the mouse + keyboard, controllers, touch, or gestures. In pc games, users often bind their movement inputs to “w”, “a”, “s”, and “d” while console gamers have their mapped to the left joystick.
Compatible input devices in Unity
- Keyboard and mouse
- Joysticks
- Controllers
- Touch screens
- Accelerometers / gyroscopes
- VR and AR
Input Manager
The input manager window allows you to define input axes and associated actions.
Mapping inputs
In the script, we add inputs in the Update()
function
void Update() {
ProcessInput();
}private void ProcessInput(){
if (Input.GetKey(KeyCode.Space)) {
print("INPUT HAS BEEN TRIGGERED!!!!");
} if (Input.GetKey(KeyCode.A)) {
rigidbody.AddRelativeForce(Vector3.left);
} else if (Input.GetKey(KeyCode.D)){
rigidbody.AddRelativeForce(Vector3.right);
} if (Input.GetKey(KeyCode.W)) {
rigidbody.AddRelativeForce(Vector3.up);
} else if (Input.GetKey(KeyCode.S)){
rigidbody.AddRelativeForce(Vector3.down);
}
}