Developing a JavaScript video game: Part 2

Developing a JavaScript video game: Part 2
by Janeth Kent Date: 06-03-2019 javascript video game course tutorial

This article is the second part of a Javascript game tutorial.

Here you can read the first part

Let's create the spaceship

Now that the background is finished, we can start setting up our space vehicle! Let's create a Player.js file and add it as a script to index.html.

In essence, we want this ship to appear near the screen's left border. We also need its anchor (position of the object) in the center of the sprite, and we can rescale it because it is perhaps too large:

class Player
        this.sprite = new PIXI.Sprite(PIXI.loader.resources["assets/spaceship.png"].texture);
        this.sprite.interactive = true;

        this.sprite.anchor.set(0.5, 0.5);
        this.sprite.position.set(renderer.width * 0.2, renderer.height * 0.4);
        this.sprite.scale.set(0.4, 0.4);


We must declare this object in the main.js file as a global variable so that it can be instantiated in the game:

var stage = new PIXI.Container();
var cloudManager;
var player;

And also in the init function of the same file:

player = new Player();

You should now see the glittering cruise of the spaceship. However, if you wait a few seconds, you should have some problems:

The spaceship now is flying behind the clouds...=_=

Yeah, because the last created object is actually moving behind the previous object. After the spacecraft is instantiated, clouds are spawning, so we need the cloud manager to generate clouds at the bottom of the object list. For this, we only need to update the CloudManager class addChild:

stage.addChildAt(, 0);

addChildAt actually allows us to pass a second parameter, that is the position in the stage’s objects list. The furthest it is, the furthest the sprite will be on the screen.

"0" basically means the first index in the list of objects, so every time we create a new cloud, we add it to the first position of the list to make sure it appears behind the spacecraft.

Now, we can start the spaceship controls.

Let's move the spaceship

Let’s work with Player.js class and add some code in the constructor:

window.addEventListener('keydown', this.onKeyDown.bind(this));
window.addEventListener('keyup', this.onKeyUp.bind(this));

This allows the game to capture keyboard events (when pressing and releasing a key). If one of these events occurs, the method is executed at the end of each line.

Now, we have to define 2 empty methods in the same class (we will fill these ones in a little while):

onKeyDown(key) = {};
onKeyUp(key) = {};

We also need 3 variables to move the spaceship: its horizontal and vertical directions (X & Y) and the speed (all of them in the constructor):

this.directionX = 0;
this.directionY = 0;
this.speed = 8;

this.keyCodes = {37: -1, 38: -1, 39: 1, 40: 1};

This object is essentially a combination of key codes and values of direction:

  • the number 37 corresponds to left arrow key, to move our spaceship to the left we need to decrease its X position.
  • the number 38 corresponds to up arrow key, to move our spaceship to the top we need to decrease its Y position.
  • the number 39 corresponds to: is the right arrow key, to move our spaceship to the right we need to increase its X position.
  • number 40 corresponds to is the down arrow key, to move our spaceship to the bottom we need to increase its Y position.

Whenever a key is pressed, the appropriate direction is retrieved:

    if (key.keyCode == 37 || key.keyCode == 39)
        this.directionX = this.keyCodes[key.keyCode];
    else if (key.keyCode == 38 || key.keyCode == 40)
        this.directionY = this.keyCodes[key.keyCode];

It looks pretty strange, but let's explain: If the key code is 37 or 39 (which means the left or right arrow key), then the X direction is set. If it's 38 or 40, you can guess what's going on (yes, it's vertical).

Now we add the update method of the player:

    this.sprite.position.x += this.directionX * this.speed;
    this.sprite.position.y += this.directionY * this.speed;

IMPORTANT: don’t forget to call it in the loop function of main.js!


If you save the game and reload it works well, except that when we release the direction keys, the ship keeps moving. It's quite evident because we haven't completed the onKeyUp function, which catches the key just released. And so, by setting either directionX or directionY to 0, we can stop it.

There's only one tiny problem: What happens if we set the direction to 0 because we released the left key, but the right key is still pressed?

The spaceship will stop, and we'd have to press the right key to move again, which is not very practical.

So why not check whether the right key or left key is still pressed so that we can reset the direction of the previous key?

What are we going to do? Firstly, we need to store the state of each key in a boolean, pressed or released. Let’s put all these states in an object variable in the Player constructor:

this.keyState = {37: false, 38: false, 39: false, 40: false};

If a key is pressed, then we just change its state to true, and if it’s released we set it to false.

Let’s add this line at the beginning of onKeyDown:

this.keyState[key.keyCode] = true;

and now, this line in onKeyUp:

this.keyState[key.keyCode] = false;

We can now proceed with the onKeyUp logic: If one of the horizontal or vertical keys is released, but the other key is still pressed, we change the direction to the last one. If both are released, we will stop the ship:

if (!this.keyState[37] && this.keyState[39])
    this.directionX = this.keyCodes[39];
else if (this.keyState[37] && !this.keyState[39])
    this.directionX = this.keyCodes[37];
else this.directionX = 0;

if (!this.keyState[38] && this.keyState[40])
    this.directionY = this.keyCodes[40];
else if (this.keyState[38] && !this.keyState[40])
    this.directionY = this.keyCodes[38];
else this.directionY = 0;

We have all set! Now, save, reload and enjoy!

Shooting rockets

What are we are miss now?

Sure! We want to shoot rockets now that we can control the ship.

Let’s start by adding the spacecraft in the assets folder and then add it to the assets loader:


Now, we'll create a new file called Rocket.js in the src folder and add it in index.html:

<script src="../src/lib/pixi.min.js"></script>
<script src="../src/Player.js"></script>
<script src="../src/CloudManager.js"></script>
<script src="../src/Rocket.js"></script>
<script src=“../src/main.js"></script>

Let’s go back to the Player class. We want it to be able to shoot a rocket if he presses the spacebar button. The onKeyDown function is already catching such events, so we just need to make a condition with the key code we want (spacebar in this example):

    this.keyState[key.keyCode] = true;

    if (key.keyCode == 32) {
        let rocket = new Rocket(this.sprite.position.x,

    if (key.keyCode == 37 || key.keyCode == 39)
        this.directionX = this.keyCodes[key.keyCode];
    else if (key.keyCode == 38 || key.keyCode == 40)
        this.directionY = this.keyCodes[key.keyCode];

We simply give the spaceship position in the Rocket constructor, so we only set its position inside the spaceship one. So, let's initialize Rocket.js with the constructor:

class Rocket
    constructor(x, y)
        this.sprite = new PIXI.Sprite(PIXI.loader.resources["assets/rocket.png"].texture);

        this.sprite.anchor.set(0.5, 0.5);
        this.sprite.position.set(x + 40, y);


Alright, if you save & reload, you may be able to fire rockets by pressing the spacebar!

Next post soon!

If you missed it, read the first part.

Read:  Developing a JavaScript video game: Part  3




Original post by  Baptiste M. 

Background vector created by photoroyalty -

by Janeth Kent Date: 06-03-2019 javascript video game course tutorial hits : 6745  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.


Related Posts

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration