To control the ball with the paddle at the bottom of the screen, you can tilt
the controller around the x-axis to move the paddle horizontally. The game
runs in a web browser, and it communicates with the Arduino via a serial
port. It reads the game controller s state several times per second to determine
the controller s current x-axis position.
Although this isn t a book about game programming, it won t hurt to take a
look at the game s innards, especially because game programming with
JavaScript is really pure fun! Also, JavaScript is very popular. It s available
on nearly every computer, because all modern web browsers come with
JavaScript interpreters.
We ll implement the game as a Google Chrome app, so make sure you ve read
Appendix 4, Controlling the Arduino with a Browser, on page
app implements the game s logic, and it talks to our game controller via serial
port. It reads the current controller state and turns it into movements of our
paddle on the screen.
Writing a GameController Class
With the
class from
SerialDevice
easy to create a
GameController
to our motion-sensing Arduino. Here s its constructor function:
BrowserGame/GameController/js/game_controller.js
var
GameController = function(path, threshold) {
this.arduino =
new
SerialDevice(path);
this.threshold = threshold || 325;
this.moveLeft = false;
this.moveRight = false;
this.buttonPressed = false;
this.boundOnReadLine = this.onReadLine.bind(this);
this.arduino.onReadLine.addListener(this.boundOnReadLine);
this.arduino.connect();
}
This function defines several properties. First, it creates a property named
arduino
and initializes it with a new
a threshold for the game controller s x-axis. To check whether a user has
tilted the game controller to the left or to the right, we need to know the con-
troller s resting point. Instead of looking for the exact resting point, we ll add
some tolerance, and that s the value we ll store in
The following three properties are all Boolean flags representing the controller s
current state. If
moveLeft
Chapter 7. Writing a Game for the Motion-Sensing Game Controller
Writing a SerialDevice Class, on page
class that provides even more convenient access
SerialDevice
object. The next property defines
is true, the user has moved the controller to the left.
www.it-ebooks.info
267. The Chrome
274, it s
.
threshold
112
report erratum
discuss
Need help?
Do you have a question about the Arduino Uno and is the answer not in the manual?