Skip to content

Instantly share code, notes, and snippets.

@CougarTown
Created March 30, 2024 21:28
Show Gist options
  • Save CougarTown/32040fe36d7c1d8aa4d954412b1b12f6 to your computer and use it in GitHub Desktop.
Save CougarTown/32040fe36d7c1d8aa4d954412b1b12f6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PlayStation Controller Button Press Detection</title>
</head>
<body>
<script>
window.addEventListener("gamepadconnected", (event) => {
console.log("Gamepad connected:", event.gamepad);
checkGamepadState();
});
window.addEventListener("gamepaddisconnected", (event) => {
console.log("Gamepad disconnected:", event.gamepad);
});
function checkGamepadState() {
requestAnimationFrame(checkGamepadState);
// Get the list of connected gamepads
const gamepads = navigator.getGamepads();
for (const gamepad of gamepads) {
if (gamepad) {
// Check button presses
for (let i = 0; i < gamepad.buttons.length; i++) {
if (gamepad.buttons[i].pressed) {
console.log(`Button ${i} pressed`);
// You can perform actions based on the pressed button here
}
}
// Check axis values
for (let i = 0; i < gamepad.axes.length; i++) {
console.log(`Axis ${i}: ${gamepad.axes[i]}`);
// You can perform actions based on the axis values here
}
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment