Keyboards

BeginnerProgrammer

The keyboard is the most common input device for desktop games. There are two ways to handle keyboard input in Xenko:

  • query key states
  • use KeyEvent listsYou can access both from the input base class. For more information about these options, see the input index

Check keyboard availability

Before handling keyboard input, check whether a keyboard is connected using Input.HasKeyboard.

Get key states

You can query key states and state changes with the following methods:

MethodDescription
IsKeyDown(Keys)Checks if a specified key is in the down state.
IsKeyPressed(Keys)Checks if a specified key has been pressed since the last update.
IsKeyReleased(Keys)Checks if a specified key has been released since the last update.
Note

Xenko doesn't support retrieving interpreted keys, such as special characters and capital letters.

Get key events

In some cases, you want to know all the keys that are currently Down, or all the keys that have been Pressed since the last update. The key state API isn't good for this situation, as you have to query each available key separately.

Instead, use the key events collections available in the Input base class.

Public ListDescription l
InputManager.DownKeysGets a list of the keys that were down in the last update.
InputManager.PressedKeysGets a list of the keys pressed in the last update.
InputManager.ReleasedKeysGets a list of the keys released in the last update.
InputManager.KeyEventsGets a list of the key events in the last update (keys pressed or released).

Every KeyEvent has two properties: Key (the affected key) and IsDown (the new state of the key).

Example code

  1. public class KeyboardEventsScript : SyncScript
  2. {
  3. //Declared public member variables and properties show in Game Studio.
  4. public override void Update()
  5. {
  6. //Perform an action in every update.
  7. if (Game.IsRunning)
  8. {
  9. if (Input.IsKeyDown(Keys.Left))
  10. {
  11. this.Entity.Transform.Position.X -= 0.1f;
  12. }
  13. if (Input.IsKeyDown(Keys.Right))
  14. {
  15. this.Entity.Transform.Position.X += 0.1f;
  16. }
  17. }
  18. }
  19. }

See also