Tuesday, 22 June 2010

Accessing Joysticks from JavaScript

Many years ago I wrote a simple browser plug-in to access game controllers from JavaScript. It was Windows only, worked in IE and Netscape 4, and it was used by quite a few JavaScript games at the time (with thousands downloads per day at its peak in 2001, mostly thanks to Scott Porter's JavaScript games). Years passed and it remained largely forgotten, with a few folks still finding it useful for robotics and other specialised cases, but no longer for games. Last year I found myself interested in the project again and decided to update the code, developing versions for Firefox on Windows and Safari on OS X, with the source to all now available under an LGPL license on Google Code (along with prebuilt installers).

Examples of using it from JavaScript, Flash and Java can be found in the project's examples folder; they're quite simple and documented, but in brief, to use it from JavaScript add joystick.js to your page:

<script type="text/javascript" src="joystick.js"></script>

Then create a new Joystick instance, which takes care of inserting the correct type of plug-in into the browser (ActiveX control for IE, NPAPI plug-in for everything else):

var joy = new Joystick();

That's about it! Using it in your game is a matter of reading the controller's axes and buttons wherever you would normally read the keys:

var joyX = joy.getX();
var joyY = joy.getY();


Using it from Flash is slightly more complicated due to having to access plug-ins via ExternalInterface, but the ActionScript Joystick class hides most of that away. Accessing it from a Java applet uses LiveConnect, but again the sample code takes care of this.

So, what are you waiting for? Bring on the games!