The Simplest Way to Use Your Smartphone as a Game Controller: A WebSocket Race Car Demo

There are some solutions out there that turn your smartphone into a Wii-style controller, but many of them require a dedicated app on your phone and even a browser plugin on your desktop. With HTML5 and WebSockets you can achieve this very quickly and easily without the need of pre-installing anything on your machine or your phone.

All you need is:

  • A desktop browser: The game is “hosted” by the desktop browser. It renders the UI of the game using HTML5 canvas and WebGL.
    Note: You can check here if your desktop browser supports WebGL.
  • A smartphone (with a browser): Smartphones can take a variety of input source, like touch, tilt, GPS, proximity, compass, camera, microphone. Many of these input sources are accessible from JavaScript, allowing you to easily control your game.
  • A WebSocket server: The desktop and the smartphone(s) have to communicate through a fast, low latency channel – exactly what WebSocket was designed to do. The WebSocket standard doesn’t provide peer-to-peer connectivity, so you’ll need a server that routes the messages between the smartphone(s) and the desktop.

If you use a WebSocket server, like the Kaazing WebSocket Gateway that provides higher-level protocols on top of WebSockets, your architecture can be kept very simple. You don’t need to write a single line of server-side code, the JavaScript code running in the desktop browser and the smartphone do all the work.

To demonstrate the power of no server-side code, we built a demo using the Java Message Service (JMS) edition of the Kaazing WebSocket Gateway. The advantage of using JMS in your JavaScript code directly is that with the pub/sub model of JMS you can very easily direct the messages between the smartphone(s) and the desktop browser.

The flow for the player is very simple:

  1. Bring up the game in your desktop browser:
  2. Enter the URL in your smartphone browser:
  3. Follow the link at the bottom of the page and enter the unique ID listed when prompted by your smartphone. This unique ID connects the game instance running in your desktop browser to the smartphone you use as your remote controller.

The race car is controlled simply by tilting your phone. Tilting the phone triggers JavaScript events which result in JMS messages sent through the WebSocket gateway to the desktop browser.

Note: For this demo to work you need a smartphone that supports the JavaScript tilt APIs. We tested the demo with devices running iOS 4 and above.

After watching the video how it works, take it for a test drive.