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.activePointeris the last one used,this.input.mousePointerthe mouse, andpointer1topointer10the touches.- There is the mouse and one touch Pointer by default (
input.activePointers: 1). For two-finger gestures, setactivePointers: 2in the game config, or callthis.input.addPointer(1). Up to 10 touch Pointers. xandyare the position in the game canvas.worldXandworldYare 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 usepointer.positionToCamera(camera)(a Vector2) orpointer.updateWorldPoint(camera).- Also:
isDown,primaryDown,button(0 left, 1 middle, 2 right),buttons,downX,downY,upX,upY,velocity,angle,distance,wasTouch,camera, andevent(the DOM event). Methods:getDistance(),getDuration(),getAngle(),leftButtonDown(),rightButtonDown(),leftButtonReleased()and so on. - Since 4.3,
leftButtonReleased()and the other*ButtonReleased()methods are no longertruewhen the button was pressed while another was held (#7254). - Right-click:
pointer.rightButtonDown(), withdisableContextMenu: truein the game config, orthis.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,cursorandpixelPerfectwithalphaTolerance(1). pixelPerfectreads 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 beforesetInteractive(). - 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) |
eventis Phaser's, not the DOM's.event.stopPropagation()stops the levels after it. The DOM event ispointer.event.- If an object in one Scene is hit, the Scenes below it don't get the event.
this.input.setGlobalTopOnly(false)changes that, andthis.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' })andthis.input.setDefaultCursor(cursor). - The wheel never scrolls the page while over the canvas, unless
input.mouse.preventDefaultWheelisfalse.
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 asdraggable: true.- In
drag,dragXanddragYare where to put the object, in its Container's space if it's in one. Indragstart, they are the offset from the object to the Pointer. - Since 4.3,
dragendgives the final drag position, the same asdrag. Before, it gave the Pointer's position within the object, which is stillgameObject.input.localXandlocalY. - A drop fires
GAMEOBJECT_DROPbeforeGAMEOBJECT_DRAG_END. The other object events areGAMEOBJECT_DRAG_START,GAMEOBJECT_DRAG_ENTER,_LEAVEand_OVER(pointer, target). - On
this.input:DRAG_START (pointer, gameObject),DRAG (pointer, gameObject, dragX, dragY),DRAG_END (pointer, gameObject, dropped), andDROP,DRAG_ENTER,DRAG_LEAVE,DRAG_OVER (pointer, gameObject, target). this.input.dragDistanceThreshold(pixels) anddragTimeThreshold(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_CHANGEis emitted onthis.input.manager.events, not onthis.input. That emitter belongs to the game, so remove the listener onSHUTDOWN.- While locked, the browser stops moving the mouse position. Since 4.3, the Pointer keeps its own
xandywhile locked, so you can move it bymovementXandmovementY, 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 fromPhaser.Input.Keyboard.KeyCodes.addKeys('W,A,S,D')oraddKeys({ up: KeyCodes.W, left: KeyCodes.A })returns an object of Keys, named as given.- A Key has
isDown,isUp,duration,timeDown,repeatsand the modifier flags.Phaser.Input.Keyboard.JustDown(key)andJustUp(key)are true once per press. A second call in the same frame returnsfalse. 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', andANY_KEY_DOWNis'keydown'. Both get the DOMKeyboardEvent. Both fire again on the OS key repeat, unless there's a Key object for that key, so checkevent.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,addKeysandcreateCursorKeyscapture 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, callthis.input.keyboard.disableGlobalCapture(), and setthis.input.keyboard.enabled = falseso the game ignores the typing. Undo both on blur. Any new capture, such asaddKey, turns global capture on again. addCapture('SPACE,UP'),removeCapture,clearCapturesandgetCaptures(). The game config'sinput.keyboard.capturetakes 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.gamepadexists only withinput: { 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.
CONNECTEDfires only for pads which connect later, so checkpad1ortotalfirst. - 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)andsetAxisThreshold(value). - The plugin's
BUTTON_DOWNandBUTTON_UPget(pad, button, value). A pad's ownGAMEPAD_BUTTON_DOWNandGAMEPAD_BUTTON_UPget(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 needsdraggable. - Listen for
POINTERLOCK_CHANGEonthis.input.manager.events. - A locked Pointer keeps its own
xandy. Move it bymovementXandmovementY. - Captured keys can't be typed into HTML inputs, and captures outlive the Scene.
keydown-Xrepeats while held, unless a Key object exists for it.createCombowith strings uses their first letters.pointer.worldXcomes from whichever Scene's Camera handled it last. UsepositionToCamera.- 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.
