Skip to content

Instantly share code, notes, and snippets.

@quantumpotato
Created August 24, 2016 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantumpotato/b6704687b50167491c5586d024d6aebb to your computer and use it in GitHub Desktop.
Save quantumpotato/b6704687b50167491c5586d024d6aebb to your computer and use it in GitHub Desktop.
gamepad
loopGamepadInput() {
var pads = navigator.getGamepads();
if (pads) {
for (var i = 0; i < pads.length; i++) {
var gp = pads[i];
if (!gp) {
break;
}
var x = gp.axes[0];
var y = gp.axes[1];
x = (x > 0.1 || x < -0.1) ? x : 0;
y = (y > 0.1 || y < -0.1) ? y : 0;
if (x == 0 && y == 0) {
x = gp.axes[2];
y = gp.axes[3];
x = (x > 0.1 || x < -0.1) ? x : 0;
y = (y > 0.1 || y < -0.1) ? y : 0;
}
if (x > 0.9) {
x = 1.0;
} else if (x < -0.9) {
x = -1.0;
}
if (y > 0.9) {
y = 1.0;
} else if (y < -0.9) {
y = -1.0;
}
var input = {'x' : x, 'y': y, 'buttons' : gp.buttons};
input = interpolateGamepad(input);
this.game.parseGamepadInput(i, input);
}
}
}
interpolateGamepad = function(input) {
var x = input.x;
var y = input.y;
var sum = Math.abs(x) + Math.abs(y);
if (sum <= 0) {
return input;
}
if (sum < 1.732050808) {
return {'x' : x, 'y': y, 'buttons' : input.buttons };
}
var xRatio = Math.abs(x) / sum;
var yRatio = Math.abs(y) / sum;
x = xRatio * x;
y = yRatio * y;
return {'x' : x, 'y': y, 'buttons' : input.buttons };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment