AI Features

Generating Enemies in the Game Using Observables

Learn to use Observables to generate enemies in the spaceship video game.

We'll cover the following...

This would be a very boring game if we didn’t have any enemies to take care of. So let’s create an infinite stream of them! We want to create a new enemy every second and a half in order to not overwhelm our hero.

Let’s look at the code for the Enemies Observable and then go through it:

var ENEMY_FREQ = 1500;
var Enemies = Rx.Observable.interval(ENEMY_FREQ)
.scan(function(enemyArray)
{
var enemy = { x: parseInt(Math.random() * canvas.width),y: -30, };
enemyArray.push(enemy);
return enemyArray;
}, []);
var Game = Rx.Observable
.combineLatest(StarStream, SpaceShip, Enemies, function(stars, spaceship, enemies)
{
return { stars: stars, spaceship: spaceship, enemies: enemies};
});
Game.subscribe(renderScene);

To create enemies, we use an interval operator to run every 1,500 milliseconds, and then use ...

Ask