JAMES LONG

Rotating Webpages with a Gamepad

December 29, 2011

Boy is it fun to have some time off. How else would I find time to implement this useless hack?

Firefox is currently implementing a Gamepad API which will be awesome for games. This functionality isn't even in the nightlies yet, but it should be soon (I'm not sure what the roadmap is). There are custom builds though for you to start using it now (more details in this hacks.mozilla.org post). People are starting to build demos with it.

I got a Wii Classic Controller for Christmas and I knew had to do something. I hooked it into my computer and the demos worked instantly in Firefox. I settled on the following hack:

It's a tiny amount of javascript that applies 3d CSS transforms as the joystick moves around. It also zooms in and out as the second joystick moves. I only implemented it for Firefox; Chrome supports a similar API in their dev builds as well. (I will add Chrome support when it gets more mainstream.)

Here it is as a bookmarklet: joystickify

And here's the code. You can refer to the Gamepad API wiki page for more info.

var x_axis = 0;
var y_axis = 0;
var forward = 1.;

window.addEventListener("MozGamepadAxisMove", function(e) {
    if(e.axis == 0) {
        x_axis = e.value;
    }
    else if(e.axis == 1) {
        y_axis = e.value;
    }
    else if(e.axis == 3) {
        if(e.value < -.05) {
            forward = Math.max(-e.value*5, 1);
        }
        else if(e.value > .05) {
            forward = 1 - e.value;
        }
        else {
            forward = 1.;
        }
    }

    var transform = 'rotate3d(1, 0, 0, ' + Math.floor(y_axis*90) + 'deg) ' + 
        'rotate3d(0, 1, 0, ' + Math.floor(x_axis*90) + 'deg) ' +
        'scale3d(' + forward + ',' + forward + ',' + forward + ')';

    document.body.style.MozTransform = transform;
    document.body.style.MozTransformOrigin = '50% 0';
}, false);

Discuss this on Hacker News