Search⌘ K
AI Features

Tracking User Input

Explore how to track and manage user keyboard input in a reactive game environment using RxJS. Understand how to maintain key state and update player position seamlessly within each frame, ensuring responsive controls and consistent rendering. This lesson guides you through building player movement logic and integrating it with your game's observable event streams.

Tracking and updating the stars was fairly simple, every frame required the same update. Let’s try something more challenging. Our game needs a player, otherwise, it’ll be pretty boring.

Instead of the same update every time, our player update function needs to figure out what keys are currently being pressed and move the player’s ship around.

Tracking keyboard state

First, we need to track keyboard state. Open gameState.ts and add the following:

TypeScript 3.3.4
// Keep track of the state of all movement keys
let keyStatus = {};
fromEvent(document, 'keydown')
.subscribe((e: any) => {
keyStatus[e.keyCode] = true;
});
fromEvent(document, 'keyup')
.subscribe((e: any) => {
keyStatus[e.keyCode] = false;
});

This keyStatus object tracks the state of the entire keyboard. We create it outside of the ...