Search⌘ K

Generating Enemies in the Game Using Observables

Explore how to generate an infinite stream of enemies in a reactive spaceship game using RxJS observables. Learn to apply interval and scan operators to manage enemy creation and movement while maintaining the game's performance and speed consistency.

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:

Javascript (babel-node)
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 the scan operator to create an array of enemies.

We briefly saw the scan operator previously while studying ...