Skip to content

Game Controllers ​Beta

scene.gameController gives a script the game controllers connected to the device: two-hand gamepads such as PlayStation and Xbox controllers on every platform, and, on Apple Vision Pro, tracked spatial controllers such as PlayStation VR2 Sense controllers and styluses such as Logitech Muse. Read the sticks and buttons every frame, react to presses as events, play haptic pulses, and follow where a tracked controller is.

Gate a portable script on the feature flag. Every Apple device has controller input; other players may not:

javascript
// Attach to: On Experience Start
if (!environment.features.has('gameController')) {
    console.log('No controller input here, showing touch controls instead');
}

Controller input reaches the experience only while its app is in front.

Connect and disconnect ​

on('connect') hands you each controller as it connects. Controllers that were already connected before your script subscribed fire connect too, on the next frame, so one handler covers both cases:

javascript
// Attach to: On Experience Start
scene.gameController.on('connect', function (controller) {
    console.log(controller.name + ' connected (' + controller.kind + ')');
});

scene.gameController.on('disconnect', function (controller) {
    console.log(controller.name + ' disconnected');
});

scene.gameController.controllers lists the connected controllers, in the order they connected. A controller that disconnects and reconnects is a new controller with a new id. Use id to tell two controllers apart, never to recognise a device.

Subscriptions end when the scene changes, as scene.on subscriptions do. The controllers and their state carry over, and the next scene's script gets connect again for every controller already present.

Read sticks and buttons ​

Each controller keeps its current state in sticks and buttons, updated in place every frame before render. Read them in a render handler:

javascript
// Attach to: On Experience Start
var SPEED = 0.5; // metres per second at full deflection
var box = scene.findEntity({ name: 'Box' });

scene.on('render', function (e) {
    var pad = scene.gameController.controllers[0];
    var stick = pad && pad.sticks.leftThumbstick;
    if (!stick || !box) {
        return;
    }
    var p = box.position;
    box.position = Vector3(p.x + stick.x * SPEED * e.deltaTime, p.y, p.z - stick.y * SPEED * e.deltaTime);
});

A stick reads { x, y }, each from -1 to 1, with up as positive y. A stick inside its dead zone reads exactly 0. The direction pad reads as a stick too.

A button reads { pressed, value, touched }. value runs from 0 to 1, so the triggers are analog:

javascript
// Attach to: On Render
var pad = scene.gameController.controllers[0];
var trigger = pad && pad.buttons.rightTrigger;
if (trigger) {
    var throttle = trigger.value; // 0 released, 1 fully pulled
}

A button or stick the controller lacks is undefined, so check before you read it. A handler throttled with scene.on('render', { throttle }) reads the newest state, which can be several frames ahead of its last run.

Names ​

KindButtonsSticks
'gamepad'buttonA, buttonB, buttonX, buttonY, leftShoulder, rightShoulder, leftTrigger, rightTrigger, leftThumbstickButton, rightThumbstickButton, buttonMenu, buttonOptionsleftThumbstick, rightThumbstick, directionPad
'spatialController'trigger, gripButton, thumbstickButton, buttonA, buttonB, buttonMenuthumbstick
'stylus'tip, primaryButton, secondaryButton

On a gamepad the face buttons go by position: buttonA is the bottom one (Cross on PlayStation, A on Xbox), buttonB the right one (Circle, B), buttonX the left one (Square, X) and buttonY the top one (Triangle, Y). On a spatial controller buttonA is the lower face button of that hand and buttonB the upper one. On a stylus tip is pressed against a surface and its value is the pressure, primaryButton is the barrel button nearest the tip, and secondaryButton the one above it, whose value says how hard it is pressed.

Read controller.kind to pick the names. controller.hand is 'left' or 'right': the side a spatial controller is built for, or the hand holding a stylus right now. A spatial controller is announced only once its side is known, so hand is set from connect on. It is null on a gamepad, for a stylus nobody holds, and where accessory tracking isn't allowed; treat null as unknown. controller.name is for display and logging, so don't branch on it.

Button events ​

controller.on('button', ...) fires when a button changes. Filter by name and phase to react to one press:

javascript
// Attach to: On Experience Start
scene.gameController.on('connect', function (controller) {
    controller.on('button', { name: 'buttonA', phase: 'began' }, function () {
        console.log('Jump');
    });
});
phaseWhen
'began'The button was pressed.
'ended'The button was released.
'changed'Its value or touched changed while it stayed pressed or released, such as a trigger pulled further.

The event carries { controller, name, phase, pressed, value, touched, aim, grip }, where aim and grip are the controller's poses in the frame of the change (see below). A trigger is a button, so the same subscription can follow how far it is pulled:

javascript
controller.on('button', { name: 'rightTrigger' }, function (e) {
    console.log('Throttle ' + Math.round(e.value * 100) + '%');
});

controller.on('stick', ...) works the same way and carries { controller, name, x, y }. Every event reports the latest state, at most once per button or stick per frame. Two consequences:

  • A press and release within one frame is not seen.
  • A button already held when the controller connected sends no 'began'; it reports 'ended' when released.

Both on methods return an id for off(id).

Haptics ​

controller.pulse(intensity, seconds) plays a haptic pulse. intensity runs from 0 to 1:

javascript
controller.on('button', { name: 'buttonA', phase: 'began' }, async function (e) {
    var started = await e.controller.pulse(0.6, 0.15);
    if (!started) {
        console.log('No haptics on this controller');
    }
});

The promise resolves once the pulse has started, not when it ends. It resolves false, with a console warning, where the controller or platform has no haptics or the controller has disconnected. Whether a new pulse cuts a running one short depends on the platform.

Tracked controllers and styluses ​

On Apple Vision Pro, spatial controllers and styluses are tracked in space. controller.aim is the pointing pose: a stylus tip, or where a spatial controller points. controller.grip is where the hand holds a spatial controller; a stylus has none. Each is a pose, null while the position isn't tracked:

Pose memberTypeDescription
positionVector3In the space of entity.worldPosition.
rotationRotationAs entity.worldRotation; the pose points along its -z.
velocityVector3Metres per second.
angularVelocityVector3Radians per second around the vector's axis.

A new pose arrives every frame; one you keep doesn't change. Follow a controller in a render handler:

javascript
// Attach to: On Experience Start
var sword = scene.findEntity({ name: 'Sword' });

scene.on('render', function () {
    var right = scene.gameController.controllers.find(function (c) {
        return c.kind === 'spatialController' && c.hand === 'right';
    });
    var grip = right && right.grip;
    if (grip && sword) {
        sword.worldPosition = grip.position;
        sword.worldRotation = grip.rotation;
    }
});

To attach an object without a script, anchor it to the accessory instead: Anchor.accessory({ kind, hand, location }) in a script, or the Spatial Accessory anchor in the editor. An anchored object hides while the accessory isn't tracked.

Gate pose reads on environment.features.has('accessoryTracking'); where it is false, poses read null. Tracking asks the person for permission the first time a script reads a pose or a hand, or lists or subscribes to controllers while a spatial controller is connected. If they decline, poses read null and the console says so once.

Controllers and the camera ​

Outside AR, such as on the Mac and in the preview, a game controller also drives the camera: the left stick and the triggers move it, and the right stick orbits. To use those inputs yourself, take them over with scene.camera.gamepad:

javascript
// Attach to: On Experience Start
scene.camera.gamepad.move = false; // the left stick and triggers are now yours; the right stick still orbits

See Camera for following an object with the camera.

Reference ​

MemberTypeDescription
scene.gameController.controllersArray<GameController>Connected controllers, in connection order.
scene.gameController.on(type, fn)string'connect' or 'disconnect'; fn receives the controller. Returns an id.
scene.gameController.off(id)Removes a subscription.
controller.idstringUnique for this connection.
controller.kindstring'gamepad', 'spatialController' or 'stylus'.
controller.handstring | null'left', 'right' or null (unknown).
controller.aimPose | nullThe pointing pose of a spatial controller or stylus, null while untracked.
controller.gripPose | nullWhere the hand holds a spatial controller, null on a stylus and while untracked.
controller.namestringFor display and logging.
controller.isConnectedbooleanfalse once disconnected; its buttons then read released and its sticks centred.
controller.buttons[name]{ pressed, value, touched }Current state, or undefined when the controller lacks the button.
controller.sticks[name]{ x, y }Current state, or undefined when the controller lacks the stick.
controller.on(type, [options], fn)string'button' or 'stick', with an optional { name, phase } filter. Returns an id.
controller.off(id)Removes a subscription.
controller.pulse(intensity, seconds)Promise<boolean>Plays a haptic pulse; resolves once it has started.