The Gamepad System is a comprehensive input handling system for browser-based games. It provides a high-level abstraction for working with gamepads, with built-in support for both generic gamepads and Xbox-specific controllers.
The Gamepad System includes a gamepad visualization system that allows you to visualize the gamepad input.
npm run dev
http://localhost:5173/test/Extensions/InputSystem/Gamepad/index.html
The system consists of three main components:
GamepadManager
: The central manager that handles gamepad connections and device creation
GamepadDevice
: Base class for gamepad functionality
XboxGamepad
: Specialized class for Xbox controllers
When initialized, the GamepadManager:
For each connected gamepad:
When a gamepad disconnects:
Each gamepad device continuously polls for:
Changes in input state trigger corresponding events:
// Create GamepadManager instance
const gamepadManager = new GamepadManager(new ManualTicker());
// Listen for gamepad connections
gamepadManager.onGamepadConnected.addObserver((gamepad) => {
console.log(`Gamepad ${gamepad.index} connected`);
});
// Listen for gamepad disconnections
gamepadManager.onGamepadDisconnected.addObserver((gamepad) => {
console.log(`Gamepad ${gamepad.index} disconnected`);
});
// Get all connected gamepads
const gamepads = gamepadManager.getAllGamepads();
// Listen for button events
gamepads[0].onButtonDown.addObserver((buttonIndex) => {
console.log(`Button ${buttonIndex} pressed`);
});
gamepads[0].onButtonUp.addObserver((buttonIndex) => {
console.log(`Button ${buttonIndex} released`);
});
// Listen for axis changes
gamepads[0].onAxisChange.addObserver(({ index, xValue, yValue }) => {
console.log(`Axis ${index} moved: x=${xValue}, y=${yValue}`);
});
// Get Xbox gamepads specifically
const xboxGamepads = gamepadManager.getXboxGamepads();
// Use Xbox-specific button events
const xbox = xboxGamepads[0];
xbox.onAButtonDown.addObserver(() => {
console.log("A button pressed");
});
xbox.onLeftTriggerChange.addObserver((value) => {
console.log(`Left trigger: ${value}`);
});
// Get stick positions
const [leftX, leftY] = xbox.getLeftStickPosition();
const [rightX, rightY] = xbox.getRightStickPosition();
Here's a complete example showing how to visualize gamepad input:
const gamepadManager = new GamepadManager(new ManualTicker());
// Create visualization for each connected gamepad
gamepadManager.onGamepadConnected.addObserver((gamepad) => {
// Create visual elements for the gamepad
const container = createGamepadVisual(gamepad.index);
// Listen for button events
gamepad.onButtonDown.addObserver((buttonIndex) => {
highlightButton(container, buttonIndex, true);
});
gamepad.onButtonUp.addObserver((buttonIndex) => {
highlightButton(container, buttonIndex, false);
});
// Listen for analog stick movement
gamepad.onAxisChange.addObserver(({ index, xValue, yValue }) => {
updateStickPosition(container, index, xValue, yValue);
});
});