Tag

Input Archives - Selfloop

Understanding : “Input” from Keyboard

By | Unity3D | No Comments

Definition: The “Input” class in unity is responsible for taking all kinds of input from difference devices. For windows, linux & Mac, we use “Input.GetKeyDown”, “Input.GetKey”,  “Input.GetKeyUp”, “Input.GetMouseButtonDown”, “Input.GetMouseButton”, “Input.GetMouseButtonUp” , “Input.mousePosition” & etc. Here, we will talk about more about how we can take input from the keyboard.

  • Input.GetKeyDown: The first frame/instance when user start pressing the key from keyboard. The return type of this function is true/false.

GetKeyDown

Let us see the following picture, Here the “GetButtonDown/GetKeyDown” Is set to true when the user is pressing the button. We will talk about more about why ““GetButton/GetKey” is also true. Here is a simple example to make player jump.

If(Input.GetKeyDown(KeyCode.Space)){

_rigidbody2D.AddForce(0.0f,500.0f);

}

  • Input.GetKey: Return true while the user is pressed and holding down the key. Here as you can see the “GetKeyDown/GetButtonDown” is false while the “GetKey/GetButton” is true. The reason why “GetButton” is true because it returns true while the user press and hold down the key where “GetButtonDown” take only the input from the first frame/instance.

GetKeyLet us consider you want to move your player to the right while your pressing and holding down your “RIGHT_ARROW_KEY”. The following code could be an example of the scenario.

If(Input.GetKey (KeyCode.RightArrow)){

            _rigidbody2D.velocity(2.0f,0.0f);

}

 

  • Input.GetKeyUp: It return true when user release the key s/he was pressing.

 GetKeyUp

Let us consider the scenario that a player is using his jet pack. By releasing the “UP_ARROW_KEY”, we want the jetpack not to go further to the top direction. To do that, we want to make the velocity over the Y-Axis to “0”, so the gravity can instantly start dragging him to the negative Y-Axis.


# The reference of the documents are taken from the “Unity – Documentation”.

Muhammad Tashfiqul Bari

Mentor at Coursera