Is it possible for a webpage to listen for button presses of a Oculus controller simply using some generic javascript code like document.addEventListener
?
In VR browsers by default the primary thumbstick scrolls the page up and down. The idea is to re-map it to trigger different actions.
From my research it looks like I need to use an A-frame but I'm looking for a generic solution that works across different websites with just Vanilla Javascript, not inside an immersive context.
It's not possible to interface with an Oculus controller outside of an immersive WebXR context.
The Inputs and Sources section of the WebXR API states:
While the Gamepad record is defined by the Gamepad API specification, it's not actually managed by the Gamepad API
So the Gamepad API will not work, and we're forced to use the WebXR API. Futhermore, we are forced to use one of the immersive modes for our webxr session. The WebXR Controller Sample states (confirmed this, see comments in rules below):
WebXR gamepads are not available during inline sessions.
That being said, you can still ...
Depending on your definition of vanilla, this will work (Codesandbox):
const gl2 = document
.querySelector('canvas.c3d')
.getContext('webgl2');
const session = await navigator.xr.requestSession('immersive-vr')
session.updateRenderState({ baseLayer: new XRWebGLLayer(session, gl2) });
const hookGamepadControls = () => {
const gamepad = session?.inputSources?.[0]?.gamepad; //replace with code to choose appropriate input source/controller
if (gamepad) {
setInterval(scroll(gamepad), 30);
}
};
session.requestAnimationFrame(hookGamepadControls); //We can request a single frame and run a timer to poll controller, no need to request additional frames
Minimum rules to follow to get Oculus or any VR/AR/XR controllers/gamepads to show up:
inline
context, only immersive-vr
or immersive-ar
(otherwise source.gamepad
will be null)source.gamepad
will be null)