Using Your Phone as a Game Controller

I was trying to come up with a presentation demo that would show off the iOS gyroscope api.  At first the best that I could come up with was a scrolling marquee.  I thought that it would be cooler than it actually was.  You know those spinning LED toys that you pick up at county fairs, amusement parks and sporting events.  Something like that.  The plan was to show text far larger than could fit on the screen.  As the screen moved the text would essentially stay in place.  So waving a device back and forth should show the entire message.  Problem: sliding horizontally does not register on the gyroscope.

My second plan was a little better.   I could use the device as a remote control for a web bowling game.  The iOS gyroscope and accelerometer data together could provide a pretty decent bowling controller.  It would not be as accurate as a Wii or PS3 controller because those controllers have the benefit of an external camera that tracks their location.  But I could calculate a swing, rotation, and twist.  So I did it.  And it works.  The swing calculations could use some tweaking for sure, but here is the gyroscope and accelerometer code:

var ballGrab = function(e) {
  playr.orient = [];

  playr.btn.removeEventListener('touchstart', ballGrab);
  playr.btn.addEventListener('touchend', ballRelease);
  window.addEventListener('devicemotion', record);
  return false;


var ballRelease = function(e) {
  playr.btn.addEventListener('touchstart', ballGrab);
  playr.btn.removeEventListener('touchend', ballRelease);
  window.removeEventListener('devicemotion', record);
  socket.emit('release', calcSwing());


var record = function(e) {
  var acl = e.accelerationIncludingGravity,
  rot = e.rotationRate;

    ax: acl.x,
    ay: acl.y,
    az: acl.z,
    ra: rot.alpha,
    rb: rot.beta,
    rg: rot.gamma

I have left out some bits of code here. The trimSwing() function goes backward through the orientation data to dump all except the data for the last forward swing. Then the calcSwing() turns the swing data into four basic values: power, acceleration, rotation, and twist.

The values are sent via to a Box2Djs front end that throws the ball into the pins. Box2Djs is equally cool. I will save that for another post. If you would like the complete code, you can find it on .

About tvalletta

I am just a guy interested in JavaScript, the Internet, Mobile, etc. I have four kids and a beautiful wife. I am an architect at the LDS Church.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s