...

/

Adding the Player’s Spaceship in the Game Using Observables

Adding the Player’s Spaceship in the Game Using Observables

Learn to use Observables to add a player to the spaceship video game.

We'll cover the following...

Now that we have our beautiful starry background, we’re ready to program the hero’s spaceship. Even though it’s the most important object in the game, our spaceship is deceptively simple. It’s an Observer of mouse moves that emits the current mouse x-coordinate and a constant y-coordinate. The player only moves horizontally, so we never need to change the y-coordinate:

Press + to interact
var HERO_Y = canvas.height - 30;
var mouseMove = Rx.Observable.fromEvent(canvas, 'mousemove');
var SpaceShip = mouseMove
.map(function(event) {
return {
x: event.clientX, y: HERO_Y };
})
.startWith({
x: canvas.width / 2, y: HERO_Y });

Notice that we used the startWith() function. This function sets the first value in the Observable, and we set it to a position ...

Access this course and 1400+ top-rated courses and projects.