360 Secure SkillHub
360 安全技能中心

input-keyboard-mouse-touch

提供 Phaser 4 中 this.input 的使用说明,覆盖指针与多点触控、交互对象和命中区域、指针事件与拖拽、指针锁定、键盘捕获与组合键及游戏手柄,并列出 v3 习惯的修正与注意事项。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:20

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/input-keyboard-mouse-touch
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
input-keyboard-mouse-touch
description
Phaser 4 input through this.input: Pointers (mouse and touch), setInteractive, hit areas and pixel-perfect hits, pointer events, dragging and drop zones, the wheel, cursors, pointer lock, multi-touch, the keyboard (createCursorKeys, addKeys for WASD, JustDown, key events, captures, combos) and gamepads. Use when making a button or anything clickable, dragging cards, moving a player with the arrows or WASD, firing on space, aiming or mouse-look, two-finger touch, gamepad controls, or typing into an HTML input over the game. Corrects v3 habits: pointerlockchange is on this.input.manager.events, not this.input; a locked Pointer keeps its x and y; addKey and createCursorKeys capture keys, which then can't be typed into HTML inputs; createCombo(['UP']) matches U; pointer.worldX can come from another Scene's Camera. Triggers on: input, pointer, click, tap, touch, mouse, drag, drop, hover, setInteractive, hit area, keyboard, WASD, cursor keys, gamepad, wheel, pointer lock.
metadata
{"phaser-version":"4.3.0"}

Input: keyboard, mouse, touch and gamepad

Pointers, interactive Game Objects, dragging, the keyboard and gamepads, through each Scene's this.input.

Source: src/input/InputPlugin.js (this.input), src/input/Pointer.js, src/input/InputManager.js, src/input/mouse/MouseManager.js, src/input/keyboard/KeyboardPlugin.js, src/input/gamepad/, src/input/events/, src/input/keyboard/events/, src/core/typedefs/InputConfig.js. Related: scenes, cameras, scale-and-responsive, phaser4-core.

Quick start

create ()
{
    const play = this.add.text(this.scale.width / 2, this.scale.height / 2, 'Play')
        .setOrigin(0.5)
        .setInteractive({ useHandCursor: true });

    play.on(Phaser.Input.Events.GAMEOBJECT_POINTER_UP, () =>
    {
        this.scene.start('Level');
    });

    this.cursors = this.input.keyboard.createCursorKeys();     // up, down, left, right, space, shift
    this.wasd = this.input.keyboard.addKeys('W,A,S,D');         // this.wasd.W and so on
}

update ()
{
    const left = this.cursors.left.isDown || this.wasd.A.isDown;
    const right = this.cursors.right.isDown || this.wasd.D.isDown;

    this.direction = (right ? 1 : 0) - (left ? 1 : 0);

    if (Phaser.Input.Keyboard.JustDown(this.cursors.space))
    {
        //  Once per press
    }
}

Pointers

A Pointer is the mouse or one touch. Each event gives you the Pointer.

  • this.input.activePointer is the last one used, this.input.mousePointer the mouse, and pointer1 to pointer10 the touches.
  • There is the mouse and one touch Pointer by default (input.activePointers: 1). For two-finger gestures, set activePointers: 2 in the game config, or call this.input.addPointer(1). Up to 10 touch Pointers.
  • x and y are the position in the game canvas. worldX and worldY are that position through the Camera of the Scene which last handled the Pointer. Pointers are shared by all Scenes, so with several Scenes or Cameras use pointer.positionToCamera(camera) (a Vector2) or pointer.updateWorldPoint(camera).
  • Also: isDown, primaryDown, button (0 left, 1 middle, 2 right), buttons, downX, downY, upX, upY, velocity, angle, distance, wasTouch, camera, and event (the DOM event). Methods: getDistance(), getDuration(), getAngle(), leftButtonDown(), rightButtonDown(), leftButtonReleased() and so on.
  • Since 4.3, leftButtonReleased() and the other *ButtonReleased() methods are no longer true when the button was pressed while another was held (#7254).
  • Right-click: pointer.rightButtonDown(), with disableContextMenu: true in the game config, or this.input.mouse.disableContextMenu().

Interactive Game Objects

const ship = this.add.sprite(200, 200, 'ship').setInteractive({ pixelPerfect: true });

const coin = this.add.image(400, 200, 'coin')
    .setInteractive(new Phaser.Geom.Circle(16, 16, 16), Phaser.Geom.Circle.Contains);

const panel = this.add.container(700, 200).setSize(240, 120).setInteractive();
  • With no arguments, the hit area is the size of the frame. A shape is in the object's local space, measured from the top-left of its frame, whatever its origin.
  • The config keys are hitArea, hitAreaCallback, draggable, dropZone, useHandCursor, cursor and pixelPerfect with alphaTolerance (1).
  • pixelPerfect reads the texture's pixels on every test, so keep it for a few objects. It doesn't work on a Container.
  • A Container needs setSize() or a hit area shape before setInteractive().
  • Since 4.3, a Shape's default hit area follows its size, such as when an Arc's radius is tweened (#7218). Hit areas you gave it don't change.
  • disableInteractive() stops input and keeps the settings. removeInteractive() removes them.
  • this.input.enableDebug(gameObject, color) draws the hit area.
  • Only the top object under the Pointer gets events (topOnly). this.input.setTopOnly(false) sends them to every object under it.
  • Hover is tested only when the Pointer moves. this.input.setPollAlways() tests every frame, for objects which move under a still Pointer.

Pointer events

Each event is emitted at three levels, in this order. The constants are on Phaser.Input.Events.

Where Constants Arguments
The Game Object GAMEOBJECT_POINTER_DOWN, _UP, _MOVE, _OVER (pointer, localX, localY, event)
GAMEOBJECT_POINTER_OUT (pointer, event)
GAMEOBJECT_POINTER_WHEEL (pointer, deltaX, deltaY, deltaZ, event)
this.input, for any object GAMEOBJECT_DOWN, _UP, _MOVE, _OVER, _OUT (pointer, gameObject, event)
GAMEOBJECT_WHEEL (pointer, gameObject, deltaX, deltaY, deltaZ, event)
this.input, anywhere POINTER_DOWN, POINTER_UP, POINTER_MOVE (pointer, currentlyOver)
POINTER_WHEEL (pointer, currentlyOver, deltaX, deltaY, deltaZ)
POINTER_DOWN_OUTSIDE, POINTER_UP_OUTSIDE (pointer)
GAME_OUT, GAME_OVER (time, event)
  • event is Phaser's, not the DOM's. event.stopPropagation() stops the levels after it. The DOM event is pointer.event.
  • If an object in one Scene is hit, the Scenes below it don't get the event. this.input.setGlobalTopOnly(false) changes that, and this.input.stopPropagation() stops the Scenes below for one event.
  • Phaser runs your handlers inside the browser's own event, so they count as a user gesture. Use pointer up for anything which needs one: fullscreen, opening a window, focusing an HTML input on iOS. On a touch screen, only the end of a touch counts.
  • Paused and sleeping Scenes get no input. Since 4.3, a cursor set by a hovered object is reset when its Scene pauses or sleeps, and set again when it resumes or wakes (#6986).
  • Cursors: setInteractive({ cursor: 'url(assets/hand.cur), pointer' }) and this.input.setDefaultCursor(cursor).
  • The wheel never scrolls the page while over the canvas, unless input.mouse.preventDefaultWheel is false.

Dragging

const card = this.add.image(200, 300, 'card').setInteractive({ draggable: true });

this.add.zone(700, 300, 160, 220).setRectangleDropZone(160, 220);

card.on(Phaser.Input.Events.GAMEOBJECT_DRAG, (pointer, dragX, dragY) =>
{
    card.setPosition(dragX, dragY);
});

card.on(Phaser.Input.Events.GAMEOBJECT_DROP, (pointer, target) =>
{
    card.setPosition(target.x, target.y);
});

card.on(Phaser.Input.Events.GAMEOBJECT_DRAG_END, (pointer, dragX, dragY, dropped) =>
{
    if (!dropped)
    {
        card.setPosition(card.input.dragStartX, card.input.dragStartY);
    }
});
  • this.input.setDraggable(gameObject) does the same as draggable: true.
  • In drag, dragX and dragY are where to put the object, in its Container's space if it's in one. In dragstart, they are the offset from the object to the Pointer.
  • Since 4.3, dragend gives the final drag position, the same as drag. Before, it gave the Pointer's position within the object, which is still gameObject.input.localX and localY.
  • A drop fires GAMEOBJECT_DROP before GAMEOBJECT_DRAG_END. The other object events are GAMEOBJECT_DRAG_START, GAMEOBJECT_DRAG_ENTER, _LEAVE and _OVER (pointer, target).
  • On this.input: DRAG_START (pointer, gameObject), DRAG (pointer, gameObject, dragX, dragY), DRAG_END (pointer, gameObject, dropped), and DROP, DRAG_ENTER, DRAG_LEAVE, DRAG_OVER (pointer, gameObject, target).
  • this.input.dragDistanceThreshold (pixels) and dragTimeThreshold (ms) delay the start, so a tap isn't a drag. Both are 0.

Pointer lock

create ()
{
    const crosshair = this.add.image(this.scale.width / 2, this.scale.height / 2, 'crosshair');

    this.input.on(Phaser.Input.Events.POINTER_UP, () =>
    {
        if (!this.input.mouse.locked)
        {
            this.input.mouse.requestPointerLock();
        }
    });

    this.input.on(Phaser.Input.Events.POINTER_MOVE, (pointer) =>
    {
        if (pointer.locked)
        {
            pointer.x = Phaser.Math.Clamp(pointer.x + pointer.movementX, 0, this.scale.width);
            pointer.y = Phaser.Math.Clamp(pointer.y + pointer.movementY, 0, this.scale.height);
        }

        crosshair.setPosition(pointer.x, pointer.y);
    });

    const onLock = (event, isLocked) => crosshair.setAlpha(isLocked ? 1 : 0.5);

    this.input.manager.events.on(Phaser.Input.Events.POINTERLOCK_CHANGE, onLock);

    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
    {
        this.input.manager.events.off(Phaser.Input.Events.POINTERLOCK_CHANGE, onLock);
    });
}
  • Request the lock from an input handler. this.input.mouse.releasePointerLock() ends it, and the player can press Esc.
  • POINTERLOCK_CHANGE is emitted on this.input.manager.events, not on this.input. That emitter belongs to the game, so remove the listener on SHUTDOWN.
  • While locked, the browser stops moving the mouse position. Since 4.3, the Pointer keeps its own x and y while locked, so you can move it by movementX and movementY, and its world position and hover follow (#7153). Before 4.3 it was reset on every event.

Keyboard

  • addKey(key, enableCapture = true, emitOnRepeat = false) takes a name such as 'SPACE' or a code from Phaser.Input.Keyboard.KeyCodes.
  • addKeys('W,A,S,D') or addKeys({ up: KeyCodes.W, left: KeyCodes.A }) returns an object of Keys, named as given.
  • A Key has isDown, isUp, duration, timeDown, repeats and the modifier flags. Phaser.Input.Keyboard.JustDown(key) and JustUp(key) are true once per press. A second call in the same frame returns false.
  • this.input.keyboard.checkDown(key, 250) is true at most once every 250 ms while held, for auto-fire.
  • removeKey(key, destroy = false, removeCapture = false).

Events, with constants on Phaser.Input.Keyboard.Events:

create ()
{
    this.input.keyboard.on(Phaser.Input.Keyboard.Events.KEY_DOWN + 'P', (event) =>
    {
        if (!event.repeat)
        {
            this.scene.pause();
            this.scene.launch('Pause');
        }
    });

    const enter = this.input.keyboard.addKey('ENTER');

    enter.on(Phaser.Input.Keyboard.Events.DOWN, (key, event) =>
    {
        //  Once per press, unless the Key has emitOnRepeat
    });
}
  • KEY_DOWN + 'P' is 'keydown-P', and ANY_KEY_DOWN is 'keydown'. Both get the DOM KeyboardEvent. Both fire again on the OS key repeat, unless there's a Key object for that key, so check event.repeat.
  • Keys and keyboard listeners are removed when the Scene shuts down. Paused and sleeping Scenes get no key events.
  • Keys are read from window (input.keyboard.target), so they still fire while the player types in an HTML input.

Captures and HTML inputs

  • addKey, addKeys and createCursorKeys capture their keys by default: the browser's default action is prevented, so space and the arrows don't scroll the page. Keys pressed with Ctrl, Alt, Shift or Meta are never prevented.
  • Captures belong to the game, not the Scene. They stay after the Scene shuts down.
  • A captured key can't be typed into an HTML <input>. While one has focus, call this.input.keyboard.disableGlobalCapture(), and set this.input.keyboard.enabled = false so the game ignores the typing. Undo both on blur. Any new capture, such as addKey, turns global capture on again.
  • addCapture('SPACE,UP'), removeCapture, clearCaptures and getCaptures(). The game config's input.keyboard.capture takes an array of key codes.

Combos

const { UP, DOWN, LEFT, RIGHT, B, A } = Phaser.Input.Keyboard.KeyCodes;

this.input.keyboard.createCombo([ UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A ], { resetOnMatch: true });

this.input.keyboard.on(Phaser.Input.Keyboard.Events.COMBO_MATCH, (combo, event) =>
{
    //  Matched
});
  • A string such as 'PHASER' is one key per letter. In an array, each string becomes its first letter, so [ 'UP', 'DOWN' ] matches U, D. Use key codes.
  • Config: resetOnWrongKey (true), maxKeyDelay (0, no limit), resetOnMatch (false), deleteOnMatch (false).

Gamepads

//  The game config needs input: { gamepad: true }
create ()
{
    this.pad = this.input.gamepad.pad1;

    if (!this.pad)
    {
        this.input.gamepad.once(Phaser.Input.Gamepad.Events.CONNECTED, (pad) =>
        {
            this.pad = pad;
        });
    }
}

update ()
{
    if (this.pad)
    {
        this.direction = this.pad.leftStick.x;     // -1 to 1

        if (this.pad.A)
        {
            //  The bottom face button
        }
    }
}
  • this.input.gamepad exists only with input: { gamepad: true } in the game config, or in the Scene's config.
  • A browser shows a pad only after a button on it is pressed, and may need HTTPS. CONNECTED fires only for pads which connect later, so check pad1 or total first.
  • On a pad: A, B, X, Y, up, down, left, right (booleans), L1, L2, R1, R2 (0 to 1), leftStick, rightStick, isButtonDown(index), getButtonValue(index), getAxisValue(index) and setAxisThreshold(value).
  • The plugin's BUTTON_DOWN and BUTTON_UP get (pad, button, value). A pad's own GAMEPAD_BUTTON_DOWN and GAMEPAD_BUTTON_UP get (index, value, button).

Input config

In the game config's input: keyboard (true), mouse (true), touch (true where the device has it), gamepad (false), activePointers (1), smoothFactor (0) and windowEvents (true, needed for the *_OUTSIDE events). mouse.preventDefaultDown, Up, Move and Wheel are all true. touch.capture is true. input: false does nothing; turn off each device instead. See src/core/typedefs/InputConfig.js.

Gotchas

  • Game Object events need setInteractive() first, and dragging also needs draggable.
  • Listen for POINTERLOCK_CHANGE on this.input.manager.events.
  • A locked Pointer keeps its own x and y. Move it by movementX and movementY.
  • Captured keys can't be typed into HTML inputs, and captures outlive the Scene.
  • keydown-X repeats while held, unless a Key object exists for it.
  • createCombo with strings uses their first letters.
  • pointer.worldX comes from whichever Scene's Camera handled it last. Use positionToCamera.
  • Do fullscreen, popups and HTML focus on pointer up, not down.
  • A Container needs a size to be interactive, and can't be pixel-perfect.