Gamepads
Gamepad Manager
First create a GamepadManager:
import { GamepadManager } from "@babylonjs/core/Gamepads/gamepadManager";const gamepadManager = new GamepadManager();Listen to the manager's gamepad connection and disconnection events:
gamepadManager.onGamepadConnectedObservable.add((gamepad, state) => {});gamepadManager.onGamepadDisconnectedObservable.add((gamepad, state) => {});Gamepad events
Once a gamepad is available, event listeners can be added to handle the gamepad's inputs.
gamepadManager.onGamepadConnectedObservable.add((gamepad, state)=>{ gamepad.onButtonDownObservable.add((button, state)=>{ //Button has been pressed console.log(button) }) gamepad.onleftstickchanged((values)=>{ //Left stick has been moved console.log(values.x+" "+values.y) })}Gamepad types
Depending on the type of controller, handle any of its unique properties:
gamepadManager.onGamepadConnectedObservable.add((gamepad, state)=>{ if (gamepad instanceof BABYLON.Xbox360Pad) { gamepad.onButtonDownObservable.add((button, state)=>{ console.log(BABYLON.Xbox360Button[button]) }) } if (gamepad instanceof BABYLON.PoseEnabledController) { gamepad.onMainButtonStateChangedObservable.add((button, state)=>{ console.log(button.value) }) const position = gamepad.devicePosition const rotation = gamepad.deviceRotationQuaternion }}Check a gamepad's current state
At any time, a gamepad's current state can be checked with the gamepad's properties:
import { Xbox360Pad } from "@babylonjs/core/Gamepads/xboxGamepad";scene.registerBeforeRender(function () { if(gamepad instanceof Xbox360Pad){ if(gamepad.buttonA){ sphere.position.y+=0.05 } sphere.position.x+=gamepad.leftStick.x*0.05 }}