Scratch for Java

Keys, mouse and controllers

In the browser, click the stage first. Only then does it get the keys.

Keys

There are two ways to ask for keys:

  • isKeyPressed(KeyCode.RIGHT) in run() asks: is the key held down right now? Use it for walking.
  • whenKeyPressed(KeyCode key) is called once per press. Use it for jumping, shooting, or opening a menu.

Key names: KeyCode.A to KeyCode.Z, KeyCode.DIGIT_0 to DIGIT_9, LEFT, RIGHT, UP, DOWN, SPACE, ENTER, ESCAPE and more. Type KeyCode. in the editor to see them all.

The mouse

Scratch Java
(mouse x) (mouse y) getMouseX(), getMouseY()
<mouse down?> isMouseDown()
when this sprite clicked whenClicked()
<touching [mouse-pointer v]?> isTouchingMousePointer()
go to [mouse-pointer v] goToMousePointer()

whenMouseClicked(MouseCode button) is called for a click anywhere on the stage. button is MouseCode.LEFT or MouseCode.RIGHT.

Game controllers

Plug in a controller and press a button, then the game finds it. The names are those of an Xbox controller: A, B, X, Y, DPAD_UP, START, …

if (Gamepad.isButtonPressed(GamepadButton.A)) {
  this.say("A!");
}
Vector2 stick = Gamepad.getStick(GamepadStick.LEFT); // x and y from -1 to 1
this.changeX(5 * stick.getX());

whenGamepadButtonPressed(GamepadButton button) works like whenKeyPressed, in a sprite or stage that implements GamepadListener.

Most games do not need any of this, though. Actions cover keys and controllers at once.

Actions

An action gives a name to something the player does, like "jump". You bind keys and controller buttons to it once. The game then only asks for the name:

  • Actions.bind(name, …) adds keys, mouse buttons, controller buttons or stick directions. Each call adds to what is there.
  • Actions.isPressed("jump") is the action's isKeyPressed.
  • Actions.getAxis("left", "right") gives one number from -1 to 1. A stick pushed a little gives a small number, so the player walks slowly.
  • whenActionPressed and whenActionReleased are called on the stage and on every sprite that implements ActionListener.

Six actions are there without binding: ui_up, ui_down, ui_left, ui_right (arrow keys, WASD, D-pad, left stick), ui_accept (Enter, Space, A) and ui_back (Escape, Backspace, B). Menus use them.

Players choose their keys

Actions.rebind("jump") waits for the next key or button and binds it to "jump". A key replaces the keys, a controller button the buttons. Escape cancels.

Actions.getBindingName("jump") gives the key to show the player, like "Space", or "A" while they use a controller.

Save the player's choice, and load it when the game starts. The text is an ID for your game, like for saving:

Actions.saveBindings("org.example.jumper"); // after the player chose
Actions.loadBindings("org.example.jumper"); // in main, after Actions.bind

The pause menu example has a menu for this.

Next

Keys, mouse and controllers

Create Shareable URL

Select Sections