Gamepad Support Added


I finally got around to looking at the javascript gamepad API. It is super easy to use. I hooked up full gamepad support for my Ludum Dare 44 game. So far I have only tested this with an XBox 360 controller but any dual stick controller should work.

Here's the bulk of the gamepad API wrapper I wrote. It is basic but gets the job done. Let me know if you try it!

var isUsingGamepad = 0;
var gamepadLeftX = 0;
var gamepadLeftY = 0;
var gamepadRightX = 0;
var gamepadRightY = 0;
var gamepadButton0 = 0
var deadZone = .1;
var maxZone = .9;

ApplyDeadZone=v=>
{
    if (v>deadZone)
        return (v-=deadZone)>maxZone? 1 : v/maxZone;
    else if (v<-deadZone)
        return (v+=deadZone)<-maxZone? -1 : v/maxZone;
    return 0;
}

UpdateGamepads=function()
{
    if (!("getGamepads" in navigator))
        return;

    // gamepad API
    var gamepad = navigator.getGamepads()[0];
    if (gamepad && gamepad.axes.length>=4 && gamepad.buttons.length>=1)
    {
        gamepadLeftX = ApplyDeadZone(gamepad.axes[0]);
        gamepadLeftY = ApplyDeadZone(gamepad.axes[1]);
        gamepadRightX = ApplyDeadZone(gamepad.axes[2]);
        gamepadRightY = ApplyDeadZone(gamepad.axes[3]);
        gamepadButton0 = gamepad.buttons[0].pressed;
        gamepadButton0 |= gamepad.buttons[9].pressed;
        
        if (Math.abs(gamepadLeftX)+Math.abs(gamepadLeftY)>.6 || gamepadButton0)
            isUsingGamepad=1
    }
}

Get SPENDOTRON: 2019

Leave a comment

Log in with itch.io to leave a comment.