Skip to content

Commit

Permalink
fix: controls in chrome
Browse files Browse the repository at this point in the history
  • Loading branch information
comatory committed Nov 7, 2023
1 parent 9c1ed9b commit 582499f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
27 changes: 20 additions & 7 deletions js/controls/gamepad.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { setGamepadIndex } from "../state/actions/controls.mjs";

// Chrome swaps gamepad axes so need to handle it
function isChrome() {
return navigator.userAgent.indexOf("Chrome") !== -1;
}

export function attachGamepadListeners(state) {
window.addEventListener("gamepadconnected", (event) => {
setGamepadIndex(event.gamepad.index, { state });
Expand All @@ -22,22 +27,27 @@ export function getGamepad(state) {

export function createCursorFromGamepad(gamepad, prevCursor, multiplier) {
const nextCursor = { x: 0, y: 0 };
const isChromeBrowser = isChrome();

const axis1 = gamepad.axes[0];
const axis2 = gamepad.axes[1];
const axis3 = gamepad.axes[2];
const axis4 = gamepad.axes[3];
const axis1 = isChromeBrowser ? gamepad.axes[1] : gamepad.axes[0];
const axis2 = isChromeBrowser ? gamepad.axes[0] : gamepad.axes[1];
const axis3 = isChromeBrowser ? null : gamepad.axes[2];
const axis4 = isChromeBrowser ? null : gamepad.axes[3];

if (Math.ceil(axis1) !== 0) {
nextCursor.y -= axis1 * multiplier;
if (isChromeBrowser) {
nextCursor.y += axis1 * multiplier;
} else {
nextCursor.y -= axis1 * multiplier;
}
}
if (Math.ceil(axis2) !== 0) {
nextCursor.x += axis2 * multiplier;
}
if (Math.ceil(axis3) !== 0) {
if (Number.isFinite(axis3) && Math.ceil(axis3) !== 0) {
nextCursor.y += axis3 * multiplier;
}
if (Math.ceil(axis4) !== 0) {
if (Number.isFinite(axis4) && Math.ceil(axis4) !== 0) {
nextCursor.x += axis4 * multiplier;
}

Expand All @@ -48,6 +58,9 @@ export function createCursorFromGamepad(gamepad, prevCursor, multiplier) {
}

export function isGamepadDirectionPressed(gamepad) {
if (isChrome()) {
return gamepad.axes.slice(0, 2).some((axis) => Math.ceil(axis) !== 0);
}
return gamepad.axes.slice(0, 3).some((axis) => Math.ceil(axis) !== 0);
}

Expand Down
2 changes: 1 addition & 1 deletion service-worker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const STATIC_CACHE_NAME = "static";
const STATIC_CACHE_VERSION = "v29";
const STATIC_CACHE_VERSION = "v30";
const STATIC_CACHE_ID = `${STATIC_CACHE_NAME}-${STATIC_CACHE_VERSION}`;

// All the files need to be added here manually. I want to avoid
Expand Down

0 comments on commit 582499f

Please sign in to comment.