Eventually, we add our own
onReadLine
listener to the
SerialDevice
object and use
our usual
bind
trick.
The
onReadLine
listener interprets the data we get from the Arduino:
BrowserGame/GameController/js/game_controller.js
GameController.prototype.onReadLine = function(line) {
const TOLERANCE = 5;
var attr = line.trim().split(' ');
if (attr.length == 4) {
this.moveRight = false;
this.moveLeft = false;
var x = parseInt(attr[0]);
if (x <= this.threshold - TOLERANCE) {
this.moveLeft = true;
} else if (x >= this.threshold + TOLERANCE) {
this.moveRight = true;
}
this.buttonPressed = (attr[3] == '1');
}
var message = 'moveLeft(' + this.moveLeft + '), ' +
'moveRight (' + this.moveRight + '), ' +
'buttonPressed(' + this.buttonPressed + ')';
console.log(message);
document.getElementById('output').innerText = message;
}
The method splits the line it receives at each blank character. Then it makes
sure that the line contains exactly four attributes. If yes, it checks whether
the current X position is to the left or to the right of the controller’s tipping
point. Note that we use the threshold value here to make the movement
detection smoother.
Finally, the method checks whether the controller’s button is currently
pressed. Also, it writes the controller’s current state to the console.
By the way, if you’d like to control the game using a Nunchuk later on (see
Chapter 9, Tinkering with the Wii Nunchuk, on page 145), you only have to
adjust the
GameController
class.
In Figure 22, The game controller communicates with a Chrome app, on page
114, you can see the output of a sample Chrome app that outputs the game
controller’s state to the JavaScript console.
We can now conveniently combine Chrome apps with our motion-sensing
controller. In the next section, you’ll learn how to create a more advanced
application using these techniques.
report erratum • discuss
Writing a GameController Class • 113
www.it-ebooks.info