Created
August 24, 2016 01:49
-
-
Save quantumpotato/b6704687b50167491c5586d024d6aebb to your computer and use it in GitHub Desktop.
gamepad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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