Skip to content

Three.js

This page adds a controller to a Three.js scene: the left stick (or WASD) moves the player relative to the camera, the right stick (or the arrow keys) turns the camera, and the bottom face button (or Space) jumps, with haptics when the player lands. Keyboard keeps working, and the SDK has no dependency on Three.js.

Terminal window
npm install @gamepadly/sdk three
import * as THREE from 'three';
import { createGamepadly } from '@gamepadly/sdk';
// 1. Input: one hub per page, and the actions the game reads.
const hub = createGamepadly();
const p1 = hub.player(0);
const actions = p1.createActions({
actions: {
jump: ['south', 'Space'], // A on Xbox, Cross on PlayStation, B on Switch
},
axes: {
moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['KeyA'], positiveKeys: ['KeyD'] },
moveZ: { stick: 'ly', negativeButtons: ['up'], positiveButtons: ['down'], negativeKeys: ['KeyW'], positiveKeys: ['KeyS'] },
turn: { stick: 'rx', negativeKeys: ['ArrowLeft'], positiveKeys: ['ArrowRight'] },
},
});
// 2. A scene: a floor and a box to move.
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 3));
scene.add(new THREE.GridHelper(40, 40));
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);
const player = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x0a84ff }));
player.position.y = 0.5;
scene.add(player);
// 3. The game loop. Three.js passes the frame time in milliseconds.
const UP = new THREE.Vector3(0, 1, 0);
const CAMERA_OFFSET = new THREE.Vector3(0, 4, 8);
const move = new THREE.Vector3();
let yaw = 0;
let velocityY = 0;
let last = performance.now();
renderer.setAnimationLoop((time) => {
const dt = Math.min(0.05, (time - last) / 1000);
last = time;
actions.update(p1.input.getState(), time); // once per frame, before reading actions
yaw -= actions.axis('turn') * 2.5 * dt;
// Pushing the stick up gives -1, which is forward (-Z) in Three.js. Rotate it to follow the camera.
move.set(actions.axis('moveX'), 0, actions.axis('moveZ')).clampLength(0, 1).applyAxisAngle(UP, yaw);
player.position.addScaledVector(move, 6 * dt);
const onGround = player.position.y <= 0.5;
if (actions.justPressed('jump') && onGround) velocityY = 7;
velocityY -= 20 * dt;
player.position.y += velocityY * dt;
if (player.position.y < 0.5) {
// Land: a harder landing plays a stronger haptic.
if (velocityY < -3) p1.haptics.playPreset('heavy_impact', { intensity: Math.min(1, -velocityY / 10) });
player.position.y = 0.5;
velocityY = 0;
}
camera.position.copy(CAMERA_OFFSET).applyAxisAngle(UP, yaw).add(player.position);
camera.lookAt(player.position);
renderer.render(scene, camera);
});
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});

renderer.setAnimationLoop() is the right place to read input: it runs once per displayed frame and keeps running in WebXR, where requestAnimationFrame stops. Call actions.update() once at the top of the callback and pass it the callback’s time, which is a performance.now() timestamp in milliseconds.

justPressed() is true for exactly one update after a press, so read it every frame. If the game runs physics at a fixed step, update the actions in the fixed step instead, or a press can land in a frame with zero physics steps. createGameLoop() from @gamepadly/sdk/loop does that for you.

  • Gamepad sticks report up as -1. In Three.js forward is -Z, so ly maps to moveZ with no inversion.
  • axis() returns -1 to 1 with the keys merged in and a 0.08 deadzone. Scale it by dt so speed does not depend on the frame rate. If a worn stick makes the camera drift, raise that axis’s deadzone.
  • Mouse look is not an action. Keep your existing pointer-lock code and add its movement to the same yaw:
let yaw = 0;
renderer.domElement.addEventListener('click', () => renderer.domElement.requestPointerLock());
addEventListener('mousemove', (e) => {
if (document.pointerLockElement === renderer.domElement) yaw -= e.movementX * 0.003;
});

Every haptic call takes a pan from -1 (left) to 1 (right). For an event in the 3D world, project its position to the screen: the projected x is already in -1 to 1.

import * as THREE from 'three';
const projected = new THREE.Vector3();
function panOf(object: THREE.Object3D, camera: THREE.Camera): number {
projected.setFromMatrixPosition(object.matrixWorld).project(camera);
return THREE.MathUtils.clamp(projected.x, -1, 1);
}
// When something explodes on the left of the screen, the player feels it on the left:
p1.haptics.playPreset('heavy_impact', { pan: panOf(explosion, camera) });

On a DualSense with 4-channel audio the pan moves between the two voice coils; on other controllers it shifts the weight between the left and right motors. See Haptics for every preset.

function destroy() {
renderer.setAnimationLoop(null);
actions.dispose();
hub.dispose(); // stops rumble and resets triggers on every controller
renderer.dispose();
}

Call destroy() when the game’s page or view goes away. With Vite, also call it from import.meta.hot.dispose(), or every hot reload adds another hub.

  • Start a new game adds button prompts, a “press any button” hint, DualSense adaptive triggers and a test that runs without a controller. All of it works unchanged in a Three.js game.
  • Using React Three Fiber? Create the hub as in the React recipe and read the actions in useFrame.