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.
Before you start
Section titled “Before you start”You should know:
- How a Behavior’s hooks work, in particular
startupandupdate(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.
How the devices are read
Section titled “How the devices are read”- 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 inupdate. A check instartupruns only once.
Keyboard
Section titled “Keyboard”Input.keyboard reports the keys of a physical keyboard.
| Member | What it returns |
|---|---|
is |
true every frame while the key is held, and for one frame after a quick tap. |
is |
true for one frame after the key went up. |
is |
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. |
Key constants
Section titled “Key constants”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, Numpad, Numpad, 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 |
|---|---|
is |
true every frame while the button is held, and for one frame after a quick click. |
is |
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 |
|---|---|---|
Mouse |
0 |
The primary button. |
Mouse |
1 |
The wheel button. |
Mouse |
2 |
The secondary button. |
Mouse |
3 |
The first side button (“back”). |
Mouse |
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.
Examples
Section titled “Examples”1. Walk, run and turn with the keyboard
Section titled “1. Walk, run and turn with the keyboard”#pragma lifecycle(update)
const WALK = 3; // metres a secondconst RUN = 2; // speed multiplier while Shift is heldconst 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');}A script reads Input.keyboard every frame: W and S walk the figure along the way it faces, A and D turn it, and Shift doubles the speed.
Click the scene, then hold W or S to walk, A or D to turn, and Shift to run. Drag to orbit the camera, scroll to zoom.
- The script only needs
update, so#pragma lifecycle(update)declares just that hook. isKeyPressedis checked every frame, so movement continues while the key is held. Multiplying bydtmakes the speed independent of the frame rate.translateZmoves the entity along its own forward axis; negative Z is forward. Turning changesrotation.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 withemitfor 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”#pragma lifecycle(startup, update)
const MIN = 0.5;const MAX = 3;const STEP = 0.001; // scale change per pixel of wheel travellet 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); }}The mouse wheel scales a model between half and three times its size, read with Input.mouse.wheelDelta(); a right click puts it back to its own size.
Turn the mouse wheel over the scene to grow or shrink the model, then right-click to reset it. Drag to orbit the camera.
wheelDelta()is the wheel travel since the previous frame, in pixels: positive when scrolling up. Most frames it is0, so the script skips the work.Math.minandMath.maxkeep the size betweenMINandMAX.scale.setScalarsets the same scale on all three axes.- A right click puts the model back to its original size.
3. Charge a throw and auto-fire
Section titled “3. Charge a throw and auto-fire”#pragma lifecycle(startup, update)
const MAX_CHARGE = 1.5; // seconds to full powerconst 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');}Hold Space to charge and release to throw a ball: the keyboard state sets the strength of an impulse on its Rigid Body.
Click the scene, then hold Space and release it to throw the ball. Drag to orbit the camera, scroll to zoom.
- While Space is held,
chargegrows bydteach frame, capped atMAX_CHARGE. - On release, the charge becomes an impulse on the ball’s rigid body, then resets.
applyImpulseis 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.
Snippets
Section titled “Snippets”1. Click an object to pick it
Section titled “1. Click an object to pick it”#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.fromScreenturns it into a ray from the camera through that point..hit()returns the nearest hit ornull.hit.entityis the entity that owns the mesh that was hit,hit.pointthe 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.
2. Tap to place, pinch to scale
Section titled “2. Tap to place, pinch to scale”#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 withphase: 'end'.- A single touch in the
endphase is a completed tap. The touch hasxandy, so it goes straight intoGraphicsRaycaster.fromScreen..ground()returns where the ray meets the level ground plane (height0), ornullif 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,
pinchStartresets so the next pinch starts fresh.
Common mistakes
Section titled “Common mistakes”- Using
isKeyPressedfor 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. UseisKeyReleasedfor actions that should happen once. - Checking input in
startup.startupruns once. Poll devices inupdate. - 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 bydt. - Expecting a character, not a key.
Key.Zis 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
idto follow one finger. - Moving a physics body through
position. Writingentity.positiondoes not move a rigid body. UsesetPosition, or the body’s methods; see Physics.