Set a dead zone on gamepad

Ok I got it working by doing pretty much what you explained and I found this awesome blog post that is a definitive reference for using the Gamepad API. I’ll post the solution here, in case someone from the future generations needs it:

export default function setDeadZone(value) {
    const DEADZONE = 0.2;

    // If stick value is smaller than dead zone, give it a value of 0
    // Math.abs() makes it work regardless of positive or negative value
    if (Math.abs(value) < DEADZONE) {

        return value = 0;

    } else {
        // We are outside the dead zone
        value = value - Math.sign(value) * DEADZONE;

        // Normalize the values between 0 and 1
        value /= (1.0 - DEADZONE);

        return value;

    }
}

And then in the gamepad updating function:

import setDeadZone from "./GamepadDeadZone";

// ...
gamepad.onleftstickchanged((values) => {

let x = values.x;
let y = values.y;
x = setDeadZone(x);
y = setDeadZone(y);
});

3 Likes