Skip to content

Keyboard, mouse and touch

Updated

The keyboard, the mouse and the touch screen are the devices almost every player has. A Behavior script reads them through Input.keyboard, Input.mouse and Input.touch: each frame, in update, it asks whether a key is held, where the mouse is, or which fingers are on the screen, and acts on the answer. This page lists every member of the three devices, the constants that name keys and buttons, and shows how to build movement, clicks, charge-ups and touch gestures with them.

You should know:

  • How a Behavior’s hooks work, in particular startup and update(dt); see Scripting.
  • What polling, the frame snapshot and pressed versus released mean; see Key concepts.
  • For clicks on objects, what a raycast is; see Picking and raycasts.
  • One reading per frame. The first question any script asks a device in a frame takes that frame’s snapshot. Every script then sees the same keys and buttons during the frame.
  • Nothing is missed. A tap or click too quick to span a frame still reads as pressed for one frame.
  • Shared with the runtime. The keyboard and mouse read the same streams the built-in components use. Keys typed into a text field are not seen, so typing does not also steer the player. Leaving the window releases every held key and button.
  • Read in update. Poll devices every frame in update. A check in startup runs only once.

Input.keyboard reports the keys of a physical keyboard.

Member What it returns
isKeyPressed(key) true every frame while the key is held, and for one frame after a quick tap.
isKeyReleased(key) true for one frame after the key went up.
isKeyPressedFor(key, seconds) While the key is held, true once every seconds: first after it has been held that long, then again each time as long again passes. 0 or less is true on every held frame.
pressedKeys() The codes of every key pressed this frame, as an array of strings.

Keys are physical key codes: they name a position on the keyboard, not the character it types. Key.W is 'KeyW', the key to the right of Q on a QWERTY layout, whatever layout the player uses. That keeps WASD controls in the same place on every keyboard.

Group Constants
Letters Key.A to Key.Z
Digits Key.Digit0 to Key.Digit9
Function keys Key.F1 to Key.F12
Numeric keypad Key.Numpad0 to Key.Numpad9, NumpadAdd, NumpadSubtract, NumpadMultiply, NumpadDivide, NumpadDecimal, NumpadEnter
Arrows ArrowUp, ArrowDown, ArrowLeft, ArrowRight
Editing and control Enter, Escape, Backspace, Tab, Space, CapsLock, Insert, Delete, Home, End, PageUp, PageDown, PrintScreen, ScrollLock, Pause, NumLock
Modifiers ShiftLeft, ShiftRight, ControlLeft, ControlRight, AltLeft, AltRight
Punctuation Minus, Equal, BracketLeft, BracketRight, Backslash, Semicolon, Quote, Backquote, Comma, Period, Slash

Left and right modifiers are separate keys. To accept either Shift, check both.

Input.mouse reports the mouse buttons, the pointer position and the wheel.

Member What it returns
isButtonPressed(button) true every frame while the button is held, and for one frame after a quick click.
isButtonReleased(button) true for one frame after the button went up. Use it for things that happen once per click.
position() The pointer as { x, y }, in CSS pixels from the top-left of the page. A new object each call.
wheelDelta() How far the wheel turned since the previous frame, in pixels: positive scrolling up, negative scrolling down, 0 when still.

MouseButton names the buttons:

Constant Value Button
MouseButton.Left 0 The primary button.
MouseButton.Middle 1 The wheel button.
MouseButton.Right 2 The secondary button.
MouseButton.XButton1 3 The first side button (“back”).
MouseButton.XButton2 4 The second side button (“forward”).

position() is in the same space that GraphicsRaycaster.fromScreen, PhysicsRaycaster.fromScreen and CoordinateSpace take, so you can pass it straight to them.

Input.touch reports fingers on a touch screen.

Member What it returns
count() How many touches this frame reports: fingers down, plus those lifted since the previous frame.
touches() This frame’s touches in the order they began, as copies.
touch(index) The touch at index in touches(), or null.
isSupported() Whether the device has a touch screen.

Each touch is a plain object:

Field What it is
id A number that stays the same for the life of one touch, from finger down to finger up.
x, y The finger’s position in CSS pixels from the top-left of the page.
phase 'start' the frame it begins, 'move' while it moves, 'stationary' while it rests, 'end' the frame it lifts, 'cancel' when the system interrupts it.

A touch can be passed to GraphicsRaycaster.fromScreen directly, because it has x and y.

KeyboardMover.jx
#pragma lifecycle(update)
const WALK = 3; // metres a second
const RUN = 2; // speed multiplier while Shift is held
const TURN = Math.PI; // radians a second
function update(dt) {
const keys = Input.keyboard;
const running = keys.isKeyPressed(Key.ShiftLeft) || keys.isKeyPressed(Key.ShiftRight);
const speed = WALK * (running ? RUN : 1) * dt;
if (keys.isKeyPressed(Key.W)) self.parent.translateZ(-speed);
if (keys.isKeyPressed(Key.S)) self.parent.translateZ(speed);
if (keys.isKeyPressed(Key.A)) self.parent.rotation.y += TURN * dt;
if (keys.isKeyPressed(Key.D)) self.parent.rotation.y -= TURN * dt;
if (keys.isKeyReleased(Key.Space)) emit('player/jump');
}
  • The script only needs update, so #pragma lifecycle(update) declares just that hook.
  • isKeyPressed is checked every frame, so movement continues while the key is held. Multiplying by dt makes the speed independent of the frame rate.
  • translateZ moves the entity along its own forward axis; negative Z is forward. Turning changes rotation.y, so W always walks the way the entity faces.
  • Both Shift keys are checked, since left and right are separate codes.
  • The jump uses isKeyReleased, so it fires once per press, and is announced with emit for another script (or a component listening to the signal) to handle.

For a real player character that collides with walls and climbs steps, use a Character Controller instead of moving the transform; see Movement.

2. Zoom with the wheel and reset with the right button

Section titled “2. Zoom with the wheel and reset with the right button”
WheelZoom.jx
#pragma lifecycle(startup, update)
const MIN = 0.5;
const MAX = 3;
const STEP = 0.001; // scale change per pixel of wheel travel
let size = 1;
let model;
function startup() {
model = findEntity('Showcase');
}
function update() {
const wheel = Input.mouse.wheelDelta();
if (wheel !== 0) {
size = Math.min(MAX, Math.max(MIN, size + wheel * STEP));
model.scale.setScalar(size);
}
if (Input.mouse.isButtonReleased(MouseButton.Right)) {
size = 1;
model.scale.setScalar(size);
}
}
  • wheelDelta() is the wheel travel since the previous frame, in pixels: positive when scrolling up. Most frames it is 0, so the script skips the work.
  • Math.min and Math.max keep the size between MIN and MAX.
  • scale.setScalar sets the same scale on all three axes.
  • A right click puts the model back to its original size.
ChargeAndFire.jx
#pragma lifecycle(startup, update)
const MAX_CHARGE = 1.5; // seconds to full power
const MAX_IMPULSE = 12;
let charge = 0;
let ball;
function startup() {
ball = findEntity('Ball').getComponent(PhysicsRigidBodyComponent);
}
function update(dt) {
const keys = Input.keyboard;
// Hold Space to charge, release to throw.
if (keys.isKeyPressed(Key.Space)) charge = Math.min(MAX_CHARGE, charge + dt);
if (keys.isKeyReleased(Key.Space)) {
const power = (charge / MAX_CHARGE) * MAX_IMPULSE;
ball.applyImpulse({ x: 0, y: power * 0.5, z: -power });
log(`Thrown at ${Math.round((charge / MAX_CHARGE) * 100)}% power`);
charge = 0;
}
// Hold F to fire four times a second.
if (keys.isKeyPressedFor(Key.F, 0.25)) emit('player/fire');
}
  • While Space is held, charge grows by dt each frame, capped at MAX_CHARGE.
  • On release, the charge becomes an impulse on the ball’s rigid body, then resets. applyImpulse is covered in Physics.
  • isKeyPressedFor(Key.F, 0.25) is true once a quarter of a second after F goes down, and again every quarter second while it stays down: an auto-fire without a timer of your own.
ClickToPick.jx
#pragma lifecycle(update)
let picked = null;
function update() {
if (!Input.mouse.isButtonReleased(MouseButton.Left)) return;
const hit = GraphicsRaycaster.fromScreen(Input.mouse.position()).hit();
if (!hit || !hit.entity) {
picked = null;
log('Clicked empty space');
return;
}
picked = hit.entity;
log(`Picked ${picked.name} at`, hit.point);
emit('picked', { id: picked.entityId });
}
  • isButtonReleased(MouseButton.Left) is true once per click, after the button goes up, like most buttons in an interface.
  • Input.mouse.position() gives the pointer in screen pixels; GraphicsRaycaster.fromScreen turns it into a ray from the camera through that point.
  • .hit() returns the nearest hit or null. hit.entity is the entity that owns the mesh that was hit, hit.point the world position of the hit.
  • The script emits the entity’s id rather than the entity, so any listener can find it again with findEntity.

For clicks on specific objects, a Selectable component with a Signal Emitter is often simpler and also works with touch and XR; see Selection and grabbing.

TouchPlaceAndPinch.jx
#pragma lifecycle(startup, update)
let target;
let pinchStart = 0;
let scaleStart = 1;
function startup() {
target = findEntity('Marker');
if (!Input.touch.isSupported()) log('No touch screen: tap and pinch are unavailable');
}
function distance(a, b) {
return Math.hypot(a.x - b.x, a.y - b.y);
}
function update() {
const touches = Input.touch.touches();
// One finger lifted: place the marker on the ground under it.
if (touches.length === 1 && touches[0].phase === 'end') {
const spot = GraphicsRaycaster.fromScreen(touches[0]).ground();
if (spot) target.position.set(spot.x, 0, spot.z);
return;
}
// Two fingers: scale the marker by how far apart they are.
if (touches.length === 2) {
const [a, b] = touches;
if (a.phase === 'start' || b.phase === 'start' || pinchStart === 0) {
pinchStart = distance(a, b);
scaleStart = target.scale.x;
} else if (pinchStart > 0) {
target.scale.setScalar(scaleStart * (distance(a, b) / pinchStart));
}
} else {
pinchStart = 0;
}
}
  • touches() lists this frame’s touches, including fingers lifted since the previous frame, which arrive with phase: 'end'.
  • A single touch in the end phase is a completed tap. The touch has x and y, so it goes straight into GraphicsRaycaster.fromScreen. .ground() returns where the ray meets the level ground plane (height 0), or null if it points at the sky.
  • With two touches, the script records their starting distance and the marker’s scale when the pinch begins, then scales by the ratio of the current distance to the starting one.
  • When fewer than two fingers remain, pinchStart resets so the next pinch starts fresh.
  • Using isKeyPressed for a one-off action. It is true on every frame the key is held, so a menu toggled with it opens and closes many times per press. Use isKeyReleased for actions that should happen once.
  • Checking input in startup. startup runs once. Poll devices in update.
  • Forgetting dt. Moving by a fixed amount per frame makes the game faster on a 120 Hz display than on a 60 Hz one. Multiply speeds by dt.
  • Expecting a character, not a key. Key.Z is a physical position. On an AZERTY keyboard it is labelled W. That is usually what you want for movement; for text entry, use a UI input field instead.
  • Following a finger by index. Touch indexes shift when an earlier finger lifts. Keep the touch’s id to follow one finger.
  • Moving a physics body through position. Writing entity.position does not move a rigid body. Use setPosition, or the body’s methods; see Physics.