Input
Volver a la referencia

Input

Keyboard, pointer and gamepad, plus named actions and the remapping layer a player owns.

57 símbolos

describeBindingfunctionnacatamalon

describeBinding(binding: TActionBinding) => string

A binding the way a person reads it: 'Space', 'A', 'L STICK LEFT'.

It lives next to the labels of the pad rather than in each controls screen, because the names and the labels are one fact: a second copy would drift, and a wrong label still draws, so nobody would be told. A key reads as its character when it is one, and a named key is split into its words ('ArrowLeft' becomes 'Arrow Left').

Parámetros

bindingTActionBinding

The binding.

Ver el código · input/actions/describe_binding.ts:31

gamepadAxisDirectionLabelfunctionnacatamalon

gamepadAxisDirectionLabel(axis: TGamepadAxisName, dir: -1 | 1) => string

How one direction of an axis reads on a controls screen: "L STICK LEFT", "L STICK DOWN".

A direction, and not an axis, is what a binding really names: an axis goes both ways and the thing bound to it does not. y grows downwards, so dir: 1 on a vertical axis is down, and writing that out is the whole point of this function: it is the one place that convention meets a person.

Parámetros

axisTGamepadAxisName

The stick axis.

dir-1 | 1

Which way along it: -1 or 1.

Ver el código · input/gamepad/gamepad_standard.ts:158

listenfunctionnacatamalon

listen(sprite: TBox | TPointerPicture, events: TSpriteEvents) => () => void

Makes a sprite, a text, a nine-slice, a set of shapes or a whole object react to the mouse and touch, after it was created.

The same events createSprite, createText and createNineSlice accept in their options (onClick, onPointerOver, onPointerOut, onPointerMove, onPointerDown, onPointerUp), for when they are not known at creation: a button that only becomes clickable when a level is cleared, or a sprite made in one place that another part of the game gives a behaviour.

  • It can be called at any moment: while the scene is built, every frame, or from another event.
  • It adds: whatever the sprite already reacted to keeps working, and two onClick both run, in the order they were connected.
  • It stops by itself when the sprite's part of the scene goes away. The function it returns stops it earlier, and removes only what this call connected.

On a sprite that has been destroyed it does nothing.

A whole object reacts as one thing. A button made of a border, a fill and a label is one button: a pointer over any of its pieces, or its children's, is over the object, and moving from the fill to the label is not leaving it. That is also how a behaviour reaches pieces it did not create, the ones a scene document or a pack made: listen(self, { onClick }). A piece that listens by itself inside it still answers for itself, being the more specific.

Parámetros

spriteTBox | TPointerPicture

The sprite, text, nine-slice, set of shapes or object that should react. A text reacts anywhere inside its block, a nine-slice anywhere inside its rectangle, a set of shapes (createShapes) as one thing wherever one of its shapes is drawn, filled or outlined, and an object over any of its pieces.

eventsTSpriteEvents

Which events, and what to do on each.

Ejemplo

export const Level: TSceneFn = () => {
    const scene = useScene();
    const door = createSprite({ key: 'door', transform: { x: 400, y: 160 } });
    let enemiesLeft = 3;
    let doorOpen = false;

    useUpdate(() => {
        // The door only becomes clickable once every enemy is gone
        if (!doorOpen && enemiesLeft === 0) {
            doorOpen = true;
            listen(door, { onClick: () => scene.change('NextLevel') });
        }
    });

    return createScene();
};
Ver el código · events/listen.ts:72

normalizeActionMapfunctionnacatamalon

normalizeActionMap(value: unknown) => TActionMap

Takes whatever came out of a file and gives back a map the engine can trust: unknown kinds of binding are dropped, keys are written the one way the keyboard writes them, repeats inside one action go (the strongest source wins at runtime, so a repeat would only be clutter in the controls screen), and an action with no name is not an action.

Total and quiet about the details: a project file is not a promise, and the game still has to run.

Parámetros

valueunknown

Whatever a file gave back, as JSON.parse left it.

Ver el código · input/actions/normalize_action_map.ts:73

useActionfunctionhooknacatamalon

useAction(name: string, options: TUseActionsOptions) => TAction

One action, which is what most game code reads.

The same as useActions with one name filled in. Reach for useActions when something reads several, and for this when it reads one.

Parámetros

namestring

The action, as the input map names it.

optionsTUseActionsOptions

Which player's devices to read, as for useActions.

Ejemplo

declare const velocity: { x: number; y: number };

const jump = useAction('jump');
useUpdate(() => { if (jump.justPressed()) velocity.y = -320; });
Ver el código · hooks/input/use_actions.ts:98

useActionsfunctionhooknacatamalon

useActions(options: TUseActionsOptions) => TActionsHandle

The game's named actions.

An action is a name, 'jump', that the game binds to whatever it likes: a key, a gamepad button, a stick direction, several at once. The game asks about the name, so the same code works on a keyboard and on a pad with no branching, and the player can change what it is bound to without the game knowing.

The list of actions is the game's: given to createGame, or written in the project's project.json by the editor.

Parámetros

optionsTUseActionsOptions

Which player's devices to read, in a game with more than one.

Ejemplo

declare const hero: TSprite;
declare const jump: () => void;
declare let charge: number;

export const Player: TSceneFn = () => {
    const input = useActions();

    useUpdate((delta) => {
        // Four actions, one direction: the keys, the d-pad and the stick all arrive here, and the
        // dead zone is round, so a gentle diagonal stays a diagonal.
        const { x, y } = input.direction('move_left', 'move_right', 'move_up', 'move_down');
        hero.transform.x += x * 120 * delta;
        hero.transform.y += y * 120 * delta;

        if (input.justPressed('jump')) jump();
        // A trigger bound to 'fire' reads how far it is pulled; a key bound to it reads 1.
        charge = input.value('fire');
    });

    return createScene();
};
Ver el código · hooks/input/use_actions.ts:73

useDirectionfunctionhooknacatamalon

useDirection(negativeX: string, positiveX: string, negativeY: string, positiveY: string, options: TUseActionsOptions & { deadzone }) => () => { x, y }

Four actions read as one direction: the way to move a character from the input map.

It gives back a function, called each frame, like the one useTween gives. The dead zone is round and applied once to the finished direction, which is what makes this identical to reading the stick when the four actions are bound to one, and what stops a gentle diagonal from collapsing onto the nearest straight line. A keyboard diagonal comes out the right length for free, which is the bug in every hand written x = right - left.

Parámetros

negativeXstring

The action that points left.

positiveXstring

The action that points right.

negativeYstring

The action that points up.

positiveYstring

The action that points down.

optionsTUseActionsOptions & { deadzone }

Which player's devices to read, and the deadzone below which the direction is zero.

Ejemplo

declare const hero: TSprite;
const SPEED = 120;

const move = useDirection('move_left', 'move_right', 'move_up', 'move_down');
useUpdate((delta) => {
    const { x, y } = move();
    hero.transform.x += x * SPEED * delta;
    hero.transform.y += y * SPEED * delta;
});
Ver el código · hooks/input/use_actions.ts:145

useDraggablefunctionhooknacatamalon

useDraggable(target: TBox | TPointerPicture, options: TUseDraggableOptions) => TDraggableHandle

Makes a sprite, a text, a nine-slice, a set of shapes or a whole object follow the pointer that drags it: pressed with the main button or a finger, it moves with it, held where it was taken, until it is let go.

Built on the drag events every sprite has (onDragStart, onDrag, onDragEnd), and adding the moving: what a card, a piece of a puzzle or an item of an inventory wants. For a drag that does not move what was pressed (a slingshot pulled back, a dial turned), use those events with listen.

  • It moves its position: an object's transform, in its parent's space, or a sprite's, in its object's. The parents may be moved, turned and scaled, and the camera may be anywhere: it stays under the pointer.
  • A click is still a click: it only starts once the pointer has moved a few pixels, and a drag never ends in onClick.
  • Dropping is said by the places: a slot made with useDropZone says what it accepts, and onDragEnd says in dropped which one it was let go into. Or by the thing dragged, with dropOn, the tags of what it may land on. With snapBack it goes back when it was none.
  • Two fingers drag two things, each its own.

It belongs to what calls it, like every hook: it stops when that goes away, and does nothing while its scene is paused. Call it while the scene or the object is built; to let something be dragged later, start it with enabled: false and call enable() then.

Only for 2D: a 3D object has nothing the pointer can pick.

Parámetros

targetTBox | TPointerPicture

What is dragged: a sprite, a text, a nine-slice, a set of shapes, or a whole object (self in a behaviour), which is dragged by any of its pieces.

optionsTUseDraggableOptions

Which way, in what steps, inside what, onto what, and what to do on the way.

Ejemplo

export const Table: TSceneFn = () => {
    const slot = createSprite({ key: 'slot', transform: { x: 240, y: 120 } });
    useTag('slot').add(slot);

    const card = createSprite({ key: 'card', transform: { x: 80, y: 120 } });
    useDraggable(card, {
        dropOn: 'slot',
        snapBack: true,
        onDragStart: () => { card.zIndex = 10; },
        onDragEnd: ({ dropped }) => {
            card.zIndex = 0;
            // Into the slot, right in the middle.
            if (dropped !== null) {
                card.transform.x = slot.transform.x;
                card.transform.y = slot.transform.y;
            }
        },
    });

    return createScene();
};
Ver el código · hooks/input/use_draggable.ts:193

useDropZonefunctionhooknacatamalon

useDropZone(target: TBox | TPointerPicture, options: TUseDropZoneOptions) => TDropZoneHandle

Makes a sprite, a text, a nine-slice, a set of shapes or a whole object a place things can be dragged into: a slot of an inventory, the square of a board, a bin.

The zone says what it accepts, by tag, and its state is asked like the keyboard's, every frame: canDrop() while something it accepts is dragged anywhere, isOver() while it is over this very zone. That is all a highlight needs, and it turns itself off when the drag ends however it ends, so nothing stays lit. onEnter, onLeave and onDrop say the same as events, at the start of the frame.

What is dragged comes from useDraggable, or from anything with drag events (onDrag in its options or with listen): useDraggable hands the zone it was dropped into in dropped, and the events in zone. When zones overlap, the one on top takes it.

It belongs to what calls it, like every hook: it goes when that goes, and does nothing while its scene is paused. To open a zone later, start it with enabled: false and call enable() then.

Parámetros

targetTBox | TPointerPicture

The place: a sprite, a text, a nine-slice, a set of shapes, or a whole object, which counts the pointer over any of its pieces.

optionsTUseDropZoneOptions

What it accepts, and what to do when something comes over it, leaves or is dropped.

Ejemplo

export const Table: TSceneFn = () => {
    const card = createSprite({ key: 'card', transform: { x: 80, y: 120 } });
    useTag('card').add(card);
    useDraggable(card, { snapBack: true });

    const slot = createSprite({ key: 'slot', transform: { x: 240, y: 120 } });
    const zone = useDropZone(slot, {
        accepts: 'card',
        onDrop: (dragged) => {
            if (dragged.transform === null) return;
            dragged.transform.x = slot.transform.x;
            dragged.transform.y = slot.transform.y;
        },
    });

    // Dim while a card could go in, bright while one is over it.
    const idle = getColor('#1e2533');
    const can = getColor('#3a4560');
    const over = getColor('#ffcc33');
    useUpdate(() => {
        slot.tint = zone.isOver() ? over : zone.canDrop() ? can : idle;
    });

    return createScene();
};
Ver el código · hooks/input/use_drop_zone.ts:128

useGamepadfunctionhooknacatamalon

useGamepad(target: TGamepadTarget, options: TUseGamepadOptions) => TGamepad

A gamepad, to ask in every frame what the player is holding, has just pressed, or how far a stick is pushed.

With no number it follows the first pad connected, which is what a one player game means. With a number it is that port and only that one, which is what local multiplayer means: player two has to keep meaning one particular controller even when player one unplugs theirs. Do not pin a single player game to port 0: the ports belong to the browser, and a pad unplugged and plugged back in usually lands in another one.

What comes back is alive. It says there is no pad while the scene is being built even with a controller plugged in, because browsers hide a pad until a button is pressed on it, and it starts saying there is one by itself when the player wakes theirs up. So read it inside useUpdate, never once at the start.

Parámetros

targetTGamepadTarget

The port, or nothing to follow the first pad connected.

optionsTUseGamepadOptions

The stick's dead zone, 0.2 by default.

Ejemplo

declare const fire: () => void;

export const Level: TSceneFn = () => {
    const pad = useGamepad();
    const keys = useKeyboard();
    const ship = createSprite({ key: 'ship' });

    useUpdate((delta) => {
        const { x, y } = pad.leftStick();
        ship.transform.x += x * 150 * delta;
        ship.transform.y += y * 150 * delta;
        if (pad.justPressed('a') || keys.justPressed('Space')) fire();
    });

    return createScene();
};
Ver el código · hooks/input/use_gamepad.ts:49

useInputMapfunctionhooknacatamalon

useInputMap() => TInputMapHandle

Remapping: what a game's controls screen is built on.

It lists the game's actions, says what each one listens to, changes them, puts them back and warns that two actions are on the same button. If the game said where to keep them, every change is written and comes back next time; starting a new game does not wipe them, because the controls are a preference and not part of a saved game.

Ejemplo

declare const jumpRow: TText;

export const Controls: TSceneFn = () => {
    const map = useInputMap();

    // "Press a key or a button for JUMP..."
    listen(jumpRow, { onClick: () => {
        map.capture((binding) => {
            if (binding === null) return;              // they pressed Escape
            if (map.conflicts(binding, 'jump').length > 0) return;
            map.bind('jump', binding, 0);
        });
    } });

    return createScene();
};
Ver el código · hooks/input/use_input_map.ts:39

useKeyboardfunctionhooknacatamalon

useKeyboard() => TKeyboard

The keyboard, to ask in every frame what the player is holding or has just pressed.

Ask it, do not wait for it. Games read the keyboard once per frame, from inside useUpdate, because that is where movement happens: isDown for what continues while a key is held, and justPressed for what happens once per press however long the key stays down.

Call it while the scene is being built, like every hook, and keep what it returns.

Ejemplo

declare const Bullet: (x: number) => void;

export const Level: TSceneFn = () => {
    const keys = useKeyboard();
    const ship = createSprite({ key: 'ship', transform: { x: 160, y: 200 } });
    const fire = useSpawn(Bullet);

    useUpdate((delta) => {
        if (keys.isDown('ArrowLeft')) ship.transform.x -= 150 * delta;
        if (keys.isDown('ArrowRight')) ship.transform.x += 150 * delta;
        if (keys.justPressed('Space')) fire(ship.transform.x);
    });

    return createScene();
};
Ver el código · hooks/input/use_keyboard.ts:39

usePointerfunctionhooknacatamalon

usePointer() => TPointerHandle

Listens to the mouse and to touch: presses, releases, movement, and what is under the pointer.

Each listener receives where the pointer is and what it is over:

  • screenX/screenY: the position on the screen, in the game's pixels, ignoring any camera.
  • worldX/worldY: the same point as a place in this scene's world, through its camera. With no camera they are the same numbers.
  • target: the sprite or text on top under the pointer, or null over empty space. hits has all of them, top first. A text is touched anywhere inside its block, gaps and spaces included.
  • button: 'main' (the left button, or a finger), 'right', 'middle'... (INPUT.POINTER_BUTTONS).
  • pointerId and pointerType: which pointer, and whether it is a 'mouse', a 'touch' or a 'pen'. Every finger has its own id from touching to lifting, so two thumbs are two pointers.

Listeners run at the start of the next frame, not the instant the browser reports the click, so anything they do behaves as it would inside useUpdate. Several movements of one pointer in one frame arrive as one, with the latest position. A touch the system takes back (a gesture of the browser's) ends as a release, never as a click, so nothing stays held.

It can also be asked, like the keyboard, from an update: isDown() while a finger is on the screen or a button is held, justPressed() and justReleased() for the one frame it went down or came up, position() for where it is, touches() for every finger, and isPressing(button) for whether a finger is on a sprite, a text, a nine-slice, a set of shapes or an object right now, which is what an on-screen button needs. An action can be bound to one, too: { type: 'touch', box: 'Jump' }.

They stop by themselves when the part of the scene that registered them goes away, and they are not called while their scene is paused. Each one returns a function that stops it earlier.

pick(x, y) asks the same question at any screen point, whenever you like.

onWheel hears the mouse wheel (or two fingers on a trackpad), with how far it turned in deltaY, and deltaX for sideways. While anything listens, the wheel over the game stops scrolling the page.

lock() captures the mouse, for a first-person camera: the cursor disappears and moving the mouse only changes movementX/movementY, as far as the hand goes, never stopping at the edge of the game. Call it from a click or a key press, which is the only time the browser allows it; Esc gives the mouse back to the player, and isLocked() says whether the game has it.

Ejemplo

export const Board: TSceneFn = () => {
    const pointer = usePointer();
    const red = getColor('#ff5566');

    pointer.onDown((info) => {
        if (info.target !== null) {
            info.target.tint = red;
        }
    });

    // The wheel zooms the camera: towards you is out, away is in.
    const camera = useCamera2d();
    pointer.onWheel(({ deltaY }) => {
        camera.zoom = Math.min(4, Math.max(0.5, camera.zoom * Math.exp(-deltaY * 0.001)));
    });

    return createScene();
};

Ejemplo

// A first-person camera: click to capture the mouse, move it to look around, Esc to let go.
export const Room: TSceneFn = () => {
    const camera = useCamera3d({ fov: 70, transform: { y: 1.6 } });
    const pointer = usePointer();

    pointer.onDown(() => {
        void pointer.lock();
    });
    pointer.onMove(({ movementX, movementY }) => {
        if (!pointer.isLocked()) {
            return;
        }
        camera.transform.rotationY -= movementX * 0.003;
        camera.transform.rotationX = clamp(camera.transform.rotationX - movementY * 0.003, -1.4, 1.4);
    });

    return createScene();
};
Ver el código · hooks/input/use_pointer.ts:101

useTouchActionfunctionhooknacatamalon

useTouchAction(action: string) => void

Makes what is being built an on-screen button for action: while a finger is on it, or on anything inside it, the action is held, and the game reads it like any other press, actions.isDown('jump'), whatever pressed it.

The button says which action it presses, so nothing has to match: no name for the action map to find it by, and a button made twice for two actions is one component given two props. A finger sliding from one button to the next moves from one action to the other, and two thumbs hold two. It counts for a handle on every device ('any').

It belongs to the button and goes with it: destroyed, it presses nothing. It is not a binding, so a controls screen never lists, changes or saves it; it is part of the game, like the button's picture. The action itself still comes from the game's map, with its other bindings: this adds a way to press it. A map in a project file binds a button of a scene by its name instead, { type: 'touch', box: 'Jump' }.

Draw the button with the engine, never as HTML over the canvas.

Parámetros

actionstring

The action a finger on it holds.

Ejemplo

declare const jump: () => void;

const Button = ({ x, action }: { x: number; action: string }) => {
    createSprite({ key: 'button', transform: { x, y: 280 } });
    useTouchAction(action);
};

export const Level: TSceneFn = () => {
    const actions = useActions();
    useSpawn(Button)({ x: 400, action: 'jump' });
    useSpawn(Button)({ x: 440, action: 'fire' });

    useUpdate(() => {
        if (actions.justPressed('jump')) jump();
    });

    return createScene();
};
Ver el código · hooks/input/use_touch_action.ts:50

TActionBindingtypenacatamalon

TActionBinding: { type, key } | { type, button } | { type, axis, dir } | { type, box } | { type, button }

One physical thing an action listens to.

Three kinds of key and pad, and the reason there is no fourth: a gamepad button covers the digital and the analogue ones alike, because a trigger already reports how far it is pressed. A separate kind for triggers would be a second name for one fact.

And touch, for an on-screen button: { type: 'touch', box: 'Jump' } holds the action while a finger is on the object named Jump (or on anything inside it). The button is an ordinary object of the scene, drawn by the engine and placed like any other, so a pad on a phone is a few sprites and the game still reads isDown('jump'), whatever pressed it. A finger sliding from one button to the next moves from one action to the other. It counts for a handle on every device ('any'). In code, a button can say itself which action it presses with useTouchAction, and needs no name; this binding is for a map written in a project file, where a scene's button has only its name.

And the mouse: { type: 'mouse', button: 'main' } is held while that button is, 'main' the left one, then 'right', 'middle', 'back' and 'forward' (INPUT.POINTER_BUTTONS). A pen counts; a finger does not, because it touches the screen for every button drawn on it and would fire whatever the click is bound to each time: fingers are touch. It belongs to the keyboard's player, so it counts for a handle on 'any' and on 'keyboard', and not on a pad's port.

dir on an axis is not a threshold and is not optional: it is part of which input this is. An axis goes both ways and an action does not, so "the horizontal axis of the left stick" does not name an input at all until it says which way.

There is deliberately no kind for a whole stick. A stick is four axis bindings across four actions: if one binding could be two-dimensional, every action would be either a number or a direction, and that split spreads into the runtime, the saved file, the editor's table and the controls screen. One direction per binding is what lets "WASD or stick or d-pad" work through the same four names with no branching in the game.

Ver el código · input/actions/types/t_action.ts:50

TActionCaptureOptionstypenacatamalon

What "press anything" listens to while it waits.

Propiedades

sourcesopcional'key' | 'button' | 'axis' | 'mouse'[]

Which kinds of input can be bound. Keys, buttons and axes by default: the mouse only when named, ['key', 'mouse'], because a controls screen is used with the mouse too, and a click on its Back button would otherwise bind itself.

deviceopcionalTActionDevice

Which pad to listen to. 'any' by default.

cancelKeyopcionalstring | null

The key that reports nothing instead of binding itself. 'Escape' by default; null turns it off, which makes a rebind the player cannot back out of, so think first.

axisThresholdopcionalnumber

How far a stick has to be pushed to count, 0 to 1. 0.7 by default: well past any dead zone, so a resting stick with a bit of drift can never bind itself.

Ver el código · input/actions/types/t_action.ts:223

TActionDeftypenacatamalon

One named action and everything it listens to.

deadzone and press are how the action feels, and they belong to the action rather than to one of its bindings: they have to be shared by every source, or the same action would mean one thing on a stick and another on a key.

Propiedades

bindingsTActionBinding[]
deadzoneopcionalnumber

Below this, the action reads as exactly 0. Default 0.2, the same as the stick's, so four actions on one stick give the same numbers as reading the stick directly.

pressopcionalnumber

How far an analogue source has to travel before it counts as pressed. Default 0.5.

A different number from the dead zone on purpose: a trigger at 30 % has a value and is not "pressed", which is what lets the same trigger be an accelerator and a trigger for firing.

Ver el código · input/actions/types/t_action.ts:68

TActionDevicetypenacatamalon

TActionDevice: number | 'any' | 'keyboard'

Which devices a reader listens to. Not a property of a binding: a property of whoever is reading, which is what makes local multiplayer the same action names read twice.

'any' (the default) is the keyboard and every pad. A number is that pad and nothing else: a keyboard is not a port, so naming a port means pad only, which is exactly what player two wants. 'keyboard' is the other half of that split.

Ver el código · input/actions/types/t_action.ts:113

TActionMaptypenacatamalon

TActionMap: TActionDef[]

A game's whole input map.

A list and not an object keyed by name, for two reasons a controls table makes obvious: renaming inside an object is a remove and an insert, which jumps the row out from under the cursor, and a repeated name can be seen and reported instead of quietly swallowed.

(The player's own changes are an object, because that one is sparse and nobody renames an action from a controls screen.)

Ver el código · input/actions/types/t_action.ts:99

TActionPersisttypenacatamalon

Where the player's own bindings are kept.

The adapter is the store's (localStorageAdapter, indexedDbAdapter or one of your own). What is deliberately not reused is the store itself: a remap is a preference, not part of a saved game, and starting a new game must not reset the controls.

Propiedades

keyopcionalstring

What to save it under. Has a prefix by default, because browser storage belongs to the whole site: a page that hosts several games would have them overwriting each other's controls.

Ver el código · input/actions/types/t_action.ts:322

TActionsHandletypenacatamalon

The actions of a game, as it reads them. Returned by useActions.

Propiedades

deviceTActionDevice

Which devices this handle is listening to.

isDown
justPressed
pressedAt
heldFor
justReleased
value
rawValue
strength
direction
has
namestypeOperator

Every action name, in the order the game declared them.

Ver el código · input/actions/types/t_action.ts:131

TDraggableDropInfotypenacatamalon

TDraggableDropInfo: TPointerDragInfo & { dropped }

What useDraggable's onDragEnd is told: the drag's info, and what it was dropped on.

Propiedades

droppedTPointerPicture | TBox | null

Where it was dropped. With dropOn, what it was let go over that carries one of those tags: the sprite, text or object itself (a set of shapes carries no tags: its object's count), or the nearest object above it that carries one. Without, the drop zone (useDropZone) it was let go over that accepts it. null when there was none.

startXnumber

Where the press began, as a place in the world through the camera as it is now: the point the pointer held it by, before it moved far enough to be a drag.

startYnumber
deltaXnumber

How far the pointer is from where the press began, in the world: worldX - startX. What a slingshot pulls back by, or a slider slides.

deltaYnumber
zoneTPointerPicture | TBox | null

The drop zone (useDropZone) under the pointer that accepts what is being dragged, or null: what it would be dropped into if it were let go now.

screenXnumber

Where on the screen, in the game's pixels from the top-left corner. Ignores any camera.

screenYnumber
worldXnumber

The same point as a place in the world, through the camera of the scene that asked for the pointer. With no camera it equals screenX/screenY.

worldYnumber
movementXnumber

How far the mouse moved since the last event, in pixels of the page rather than of the game, so the same move of the hand turns a camera the same amount however big the game is shown. Every move since the last frame is added together. 0 for a press, a release or the wheel.

The number a mouse-look camera wants, and the only one that changes while the pointer is captured (lock): then the cursor is hidden and screenX/screenY stay where it was.

movementYnumber
buttonTPointerButtonName

Which button: 'main' (the left, or a finger), 'middle' (the wheel pressed), 'right', and 'back' and 'forward' on the side of some mice. All of them in INPUT.POINTER_BUTTONS.

pointerIdnumber

Which pointer this is: each finger on a touch screen has its own, the same from the moment it touches until it lifts, so two thumbs (one on the throttle, one steering) are told apart. The mouse keeps one for good.

pointerTypeTPointerType

What it is: 'mouse', 'touch' (a finger) or 'pen'. A game can show its on-screen buttons only once the player has touched.

timenumber

When it happened, in seconds on the page's clock: the moment the finger touched or the button went down, which can be up to a frame before the frame that tells of it. What a rhythm game judges a tap by: song.positionAt(info.time).

targetTPointerPicture | null

The sprite, text, nine-slice or set of shapes on top under the pointer, or null over empty space.

hitsReadonlyArray<TPointerPicture>

Every sprite, text, nine-slice and set of shapes under the pointer, the one on top first.

Ver el código · hooks/input/use_draggable.ts:18

TGamepadtypenacatamalon

One pad, as a game reads it. Returned by useGamepad.

Everything here is live: a handle taken while the scene is being built says there is no pad, and starts saying there is one by itself when the player's shows up. That matters more than it sounds, because browsers hide a pad until a button is pressed on it (so that a page cannot tell who you are by your hardware): "no pad" is the normal state at the start of a scene even with a controller plugged in.

Held and just pressed split exactly like the keyboard's, and for the same reason: hold left to walk, justPressed('a') to jump once however long the button is held.

One thing it cannot do, and it is the browser's limit rather than a choice: a press and a release that both happen between two frames leave no trace. A pad sends no events, it can only be asked how it is now, so "what happened since the last frame" is a comparison of two answers. At 60 frames a second that is a tap under 16 ms, which no thumb produces on a real button. The keyboard does catch that case, because it gets real events.

Propiedades

indexnumber

The port being read right now. Fixed for a handle pinned to a number; for one that follows the first pad, it changes when pads are plugged in or out.

connectedboolean

Whether there is a pad in that port right now.

idstring

What the browser calls it, or empty with nothing connected.

mappingstring

'standard', or empty for a pad the browser did not recognise.

buttonCountnumber

How many buttons the pad says it has, 0 with nothing connected.

axisCountnumber

How many axes the pad says it has, 0 with nothing connected.

isDown
justPressed
justReleased
pressedAt
value
axis
leftStick
rightStick
deadzonenumber

The dead zone this handle uses, 0 to 1.

setDeadzone
rawButton
rawButtonValue
rawJustPressed
rawJustReleased
rawAxis
canRumbleboolean

Whether the browser offers vibration for this pad, so an options screen can grey out its switch instead of offering one that does nothing.

rumble
stopRumble
onConnect
onDisconnect
Ver el código · input/gamepad/types/t_gamepad.ts:92

TGamepadAxisNametypenacatamalon

TGamepadAxisName: 'leftX' | 'leftY' | 'rightX' | 'rightY'

A stick axis of the standard mapping. X grows to the right and Y grows downwards, which is what the browser reports and also how this engine measures the screen: pushing the stick up gives a negative leftY, the same sign a sprite needs to move up.

Ver el código · input/gamepad/gamepad_standard.ts:36

TGamepadButtonNametypenacatamalon

TGamepadButtonName: 'a' | 'b' | 'x' | 'y' | 'lb' | 'rb' | 'lt' | 'rt' | 'back' | 'start' | 'ls' | 'rs' | 'up' | 'down' | 'left' | 'right' | 'guide'

A button of the W3C standard mapping, by the name this engine gives it.

The names are the Xbox labels because that is how the specification itself defines the mapping: "the bottom button of the right cluster" is index 0, and every pad that reports mapping: 'standard' has agreed to put its bottom face button there.

Worth knowing before the first bug report: on a Nintendo or an 8BitDo pad the printed letters sit in the other order, so the button under the player's thumb when they press 'a' is the one labelled B on the plastic. That is the pad's labelling, not a mistake here: the position is what the standard mapping promises, and the position is what a game cares about.

A closed list of seventeen, so a typo is caught when the game is compiled.

Ver el código · input/gamepad/gamepad_standard.ts:19

TGamepadInfotypenacatamalon

What a pad says about itself when it arrives or leaves.

mapping is the field worth reading: 'standard' means the button names line up with the plastic, and anything else (usually an empty string) is a pad the browser did not recognise, one of those cheap USB copies of a SNES or Mega Drive controller, whose buttons land wherever the manufacturer put them. Those are still perfectly playable through rawButton and rawAxis; what does not work on them are the names, and this is how a game finds that out instead of quietly reading the wrong button.

Propiedades

indexnumber

The port it is plugged into, the same number useGamepad(port) takes.

idstring

What the browser calls it, something like 'Xbox Wireless Controller (…)'.

mappingstring

'standard' when the names can be trusted, usually empty otherwise.

buttonCountnumber
axisCountnumber
Ver el código · input/gamepad/types/t_gamepad.ts:17

TGamepadTargettypenacatamalon

TGamepadTarget: number | 'first'

Which pad a handle reads: a port number, or the first one connected.

The difference is not fussiness. The browser owns the port, not the player: a pad unplugged and plugged back in usually lands in a different one, so a single player game nailed to port 0 goes silent with nothing in the console to say why. Following the first pad is what such a game actually means; a number is what local multiplayer means, where "player two" has to keep meaning one particular controller.

Ver el código · input/gamepad/types/t_gamepad.ts:240

TKeyNametypenacatamalon

TKeyName: string

A key, spelled the way the browser reports it in KeyboardEvent.key: space is ' ', letters are lowercase ('f'), and named keys keep their names ('ArrowLeft', 'Escape', 'Enter'). 'Space' is accepted for the space bar too.

An alias of string, so any literal still fits without a cast. What it buys is the name showing up in a signature, which says what kind of string is expected.

Ver el código · input/types/t_key_name.ts:13

TPointerButtonNametypenacatamalon

TPointerButtonName: 'main' | 'middle' | 'right' | 'back' | 'forward'

A button of the mouse, by the name this engine gives it. A finger is 'main'.

'main' and not 'left': on a mouse set up for the left hand the main button is the right one, and a finger is neither. 'back' and 'forward' are the two on the side of some mice.

Ver el código · input/pointer_buttons.ts:11

TPointerDragInfotypenacatamalon

TPointerDragInfo: TPointerInfo & { startX, startY, deltaX, deltaY, zone }

What a drag listener is told: everything a pointer listener is, and where the drag began.

target and hits are what is under the thing being dragged, never the thing itself or its pieces: what it would be dropped on, which is what onDragEnd wants to know. A drag the system takes back (a gesture of the browser's) ends over nothing, with target null.

Propiedades

startXnumber

Where the press began, as a place in the world through the camera as it is now: the point the pointer held it by, before it moved far enough to be a drag.

startYnumber
deltaXnumber

How far the pointer is from where the press began, in the world: worldX - startX. What a slingshot pulls back by, or a slider slides.

deltaYnumber
zoneTPointerPicture | TBox | null

The drop zone (useDropZone) under the pointer that accepts what is being dragged, or null: what it would be dropped into if it were let go now.

screenXnumber

Where on the screen, in the game's pixels from the top-left corner. Ignores any camera.

screenYnumber
worldXnumber

The same point as a place in the world, through the camera of the scene that asked for the pointer. With no camera it equals screenX/screenY.

worldYnumber
movementXnumber

How far the mouse moved since the last event, in pixels of the page rather than of the game, so the same move of the hand turns a camera the same amount however big the game is shown. Every move since the last frame is added together. 0 for a press, a release or the wheel.

The number a mouse-look camera wants, and the only one that changes while the pointer is captured (lock): then the cursor is hidden and screenX/screenY stay where it was.

movementYnumber
buttonTPointerButtonName

Which button: 'main' (the left, or a finger), 'middle' (the wheel pressed), 'right', and 'back' and 'forward' on the side of some mice. All of them in INPUT.POINTER_BUTTONS.

pointerIdnumber

Which pointer this is: each finger on a touch screen has its own, the same from the moment it touches until it lifts, so two thumbs (one on the throttle, one steering) are told apart. The mouse keeps one for good.

pointerTypeTPointerType

What it is: 'mouse', 'touch' (a finger) or 'pen'. A game can show its on-screen buttons only once the player has touched.

timenumber

When it happened, in seconds on the page's clock: the moment the finger touched or the button went down, which can be up to a frame before the frame that tells of it. What a rhythm game judges a tap by: song.positionAt(info.time).

targetTPointerPicture | null

The sprite, text, nine-slice or set of shapes on top under the pointer, or null over empty space.

hitsReadonlyArray<TPointerPicture>

Every sprite, text, nine-slice and set of shapes under the pointer, the one on top first.

Ver el código · input/types/t_pointer.ts:121

TPointerHandletypenacatamalon

The mouse and touch input a scene reads, returned by usePointer.

Propiedades

onDown
onUp
onMove
onWheel
pick
isDown
justPressed
justReleased
pressedAt
position
touches
isPressing
lock
unlock
isLocked
Ver el código · input/types/t_pointer.ts:225

TPointerInfotypenacatamalon

What a pointer listener is told: where the mouse or finger is, which button, and what is under it.

Propiedades

screenXnumber

Where on the screen, in the game's pixels from the top-left corner. Ignores any camera.

screenYnumber
worldXnumber

The same point as a place in the world, through the camera of the scene that asked for the pointer. With no camera it equals screenX/screenY.

worldYnumber
movementXnumber

How far the mouse moved since the last event, in pixels of the page rather than of the game, so the same move of the hand turns a camera the same amount however big the game is shown. Every move since the last frame is added together. 0 for a press, a release or the wheel.

The number a mouse-look camera wants, and the only one that changes while the pointer is captured (lock): then the cursor is hidden and screenX/screenY stay where it was.

movementYnumber
buttonTPointerButtonName

Which button: 'main' (the left, or a finger), 'middle' (the wheel pressed), 'right', and 'back' and 'forward' on the side of some mice. All of them in INPUT.POINTER_BUTTONS.

pointerIdnumber

Which pointer this is: each finger on a touch screen has its own, the same from the moment it touches until it lifts, so two thumbs (one on the throttle, one steering) are told apart. The mouse keeps one for good.

pointerTypeTPointerType

What it is: 'mouse', 'touch' (a finger) or 'pen'. A game can show its on-screen buttons only once the player has touched.

timenumber

When it happened, in seconds on the page's clock: the moment the finger touched or the button went down, which can be up to a frame before the frame that tells of it. What a rhythm game judges a tap by: song.positionAt(info.time).

targetTPointerPicture | null

The sprite, text, nine-slice or set of shapes on top under the pointer, or null over empty space.

hitsReadonlyArray<TPointerPicture>

Every sprite, text, nine-slice and set of shapes under the pointer, the one on top first.

Ver el código · input/types/t_pointer.ts:14

TPointerLockOptionstypenacatamalon

How the mouse is captured, for usePointer().lock.

Propiedades

rawopcionalboolean

The mouse's own movement, without the system's acceleration, where the browser offers it. Default false.

Ver el código · input/types/t_pointer.ts:335

TPointerTouchtypenacatamalon

A pointer that is pressing right now, a finger on the screen or a mouse button held, as usePointer().touches() lists them.

Propiedades

pointerIdnumber
pointerTypeTPointerType
screenXnumber

Where it is now, in the game's pixels from the top-left corner, ignoring any camera.

screenYnumber
worldXnumber

The same point through the camera of the scene that asked.

worldYnumber
Ver el código · input/types/t_pointer.ts:86

TPointerWheelInfotypenacatamalon

TPointerWheelInfo: TPointerInfo & { deltaY, deltaX }

What a wheel listener is told: everything a pointer listener is, and how far the wheel turned.

In pixels whichever way the browser counted them (some mice count lines, some pages), so one notch of an ordinary mouse wheel is around a hundred. Every turn since the last frame is added together: a quick spin is one call with a large number, not several small ones a frame apart.

Propiedades

deltaYnumber

How far the wheel turned. Positive is turning it towards you, which scrolls a page down and which most games read as zooming out; a trackpad scrolls this way when two fingers go up.

deltaXnumber

Sideways, from a tilting wheel or a trackpad. Positive is to the right.

screenXnumber

Where on the screen, in the game's pixels from the top-left corner. Ignores any camera.

screenYnumber
worldXnumber

The same point as a place in the world, through the camera of the scene that asked for the pointer. With no camera it equals screenX/screenY.

worldYnumber
movementXnumber

How far the mouse moved since the last event, in pixels of the page rather than of the game, so the same move of the hand turns a camera the same amount however big the game is shown. Every move since the last frame is added together. 0 for a press, a release or the wheel.

The number a mouse-look camera wants, and the only one that changes while the pointer is captured (lock): then the cursor is hidden and screenX/screenY stay where it was.

movementYnumber
buttonTPointerButtonName

Which button: 'main' (the left, or a finger), 'middle' (the wheel pressed), 'right', and 'back' and 'forward' on the side of some mice. All of them in INPUT.POINTER_BUTTONS.

pointerIdnumber

Which pointer this is: each finger on a touch screen has its own, the same from the moment it touches until it lifts, so two thumbs (one on the throttle, one steering) are told apart. The mouse keeps one for good.

pointerTypeTPointerType

What it is: 'mouse', 'touch' (a finger) or 'pen'. A game can show its on-screen buttons only once the player has touched.

timenumber

When it happened, in seconds on the page's clock: the moment the finger touched or the button went down, which can be up to a frame before the frame that tells of it. What a rhythm game judges a tap by: song.positionAt(info.time).

targetTPointerPicture | null

The sprite, text, nine-slice or set of shapes on top under the pointer, or null over empty space.

hitsReadonlyArray<TPointerPicture>

Every sprite, text, nine-slice and set of shapes under the pointer, the one on top first.

Ver el código · input/types/t_pointer.ts:197

TRumbleOptionstypenacatamalon

How hard and how long to shake the pad. Everything is optional: rumble() on its own is a short generic thump, which is what most calls want.

Propiedades

durationopcionalnumber

Seconds, default 0.2, never more than 5: past that the browser cuts it without saying so.

strongopcionalnumber

The heavy motor, 0 to 1, default 1. The one felt as a thud.

weakopcionalnumber

The light motor, 0 to 1, default 1. The one felt as a buzz.

delayopcionalnumber

Seconds to wait before starting, default 0.

Ver el código · input/gamepad/types/t_gamepad.ts:51

TSpriteEventstypenacatamalon

What a sprite or a text can react to by itself: in createSprite's or createText's options, or connected later with listen. Every one receives where the pointer is and what is under it. A text reacts anywhere inside its block, the gaps between letters included.

Propiedades

onPointerOveropcionalTPointerListener

The pointer comes over the sprite.

onPointerOutopcionalTPointerListener

The pointer stops being over it, or leaves the game.

onPointerMoveopcionalTPointerListener

The pointer moves while over it.

onPointerDownopcionalTPointerListener

A button is pressed, or a finger touches, over it.

onPointerUpopcionalTPointerListener

A button is released, or a finger lifts, over it.

onClickopcionalTPointerListener

Pressed and released without leaving it. The cursor turns into a hand over it.

onDragStartopcionalTPointerDragListener

Pressed with the main button (or a finger) and moved far enough not to be a click: a few pixels of the page, more for a finger, which shakes. Once it starts, the press is a drag and not a click: letting go over it does not call onClick. The cursor turns into an open hand over something that can be dragged, and a closed one while it is.

Nothing moves by itself: the events say what the pointer did, and the game decides what that does (follow it, pull a slingshot back, turn a dial). useDraggable is the one that moves it.

onDragopcionalTPointerDragListener

The pointer that started the drag moved, wherever it is: over the sprite or not, in the game or off its edge. Called right after onDragStart too, so the first move is not lost.

onDragEndopcionalTPointerDragListener

The pointer that dragged it let go, with target and hits saying what it was let go over.

Ver el código · input/types/t_sprite_events.ts:12

TUseActionsOptionstypenacatamalon

What the action hooks accept.

Propiedades

deviceopcionalTActionDevice

Which devices to listen to. 'any' (the default) is the keyboard and every pad, which is one player. A port number is that pad and nothing else, which is how two players share one set of action names; 'keyboard' is the other half of that split.

Ver el código · hooks/input/use_actions.ts:12

TUseDraggableOptionstypenacatamalon

How useDraggable moves what it is given.

Propiedades

axisopcional'both' | 'x' | 'y'

Which way it can go: 'both', or only along 'x' (a slider) or 'y'.

gridopcionalnumber

Steps it keeps to, in pixels: it lands on multiples of this. 0 moves freely.

boundsopcional{ x, y, width, height }

A rectangle it does not leave, measured where its position is: in its parent's space for an object, in its object's for a sprite. Its position stays inside, not its whole picture.

dropOnopcionalstring | typeOperator

The tags of what it may be dropped on, one or several (useTag, or the tags of a box in a scene). Let go over one, onDragEnd says which in dropped. Left out, the drop zones (useDropZone) decide, by what they accept.

snapBackopcionalboolean

Goes back to where the drag began when it is let go anywhere it may not be dropped: off every thing tagged dropOn, or, without dropOn, off every drop zone that accepts it.

enabledopcionalboolean

Whether it can be dragged from the start. enable() lets it later.

onDragStartopcional(info: TPointerDragInfo) => void

It began to move.

onDragopcional(info: TPointerDragInfo) => void

It moved, already where the pointer took it.

onDragEndopcional(info: TDraggableDropInfo) => void

It was let go, already where it stays (or back, with snapBack).

Ver el código · hooks/input/use_draggable.ts:35

TUseDropZoneOptionstypenacatamalon

What a drop zone accepts, and what it is told.

Propiedades

acceptsopcionalstring | typeOperator

The tags of what it accepts, one or several: what is dragged carries one of them, or an object it sits in does. A slot for cards, 'card'; a bin for anything thrown away, ['card', 'coin']. Everything that can be dragged, when left out.

enabledopcionalboolean

Whether it takes things from the start. enable() lets it later.

onEnteropcionalTDropZoneListener

Something it accepts is dragged over it.

onLeaveopcionalTDropZoneListener

It is dragged off it again, let go, or the drag was taken back.

onDropopcionalTDropZoneListener

It was let go over it. Called after what was dragged hears onDragEnd, so what is done here (putting it in the middle of the slot) has the last word. onLeave follows.

Ver el código · hooks/input/use_drop_zone.ts:14

TUseGamepadOptionstypenacatamalon

What useGamepad accepts.

Propiedades

deadzoneopcionalnumber

Stick dead zone, 0 to 1. Default 0.2: inside the value Xbox pads themselves suggest, and above the drift of the cheap pads this engine's players will really own.

Ver el código · input/gamepad/types/t_gamepad.ts:249