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 : 5056  
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 END DEVELOPMENT.


Related Posts

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

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