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 : 7679  
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 upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

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…