Developing a Javascript Video Game: Part 1

Developing a JavaScript video game: Part 1
by Janeth Kent Date: 17-02-2019 javascript video game course tutorial


The ecosystem of JavaScript is pretty huge. But today we decided to try something new: a videogame.

It is usually good to have requirements in place to select the right tool for the job (or the most glittering tool for the job) before evaluating any technology choice.

Not surprisingly, JavaScript has a lot of libraries and game engines to choose from, HTML5 game engines and this Github Wiki offers some options.

After some research, in particular reading Reddit threads and looking at the websites of the most popular frameworks, we take these 5 game frameworks into account:

  1. Phaser  A fast, fun and free open source HTML5 game framework, looks like it has many features, ooh Opal support.
  2. Pixi.js 2D webGL renderer with canvas fallback, its fast?!
  3. Create.js A suite of JavaScript libraries and tools designed for working with HTML5, not just games.
  4. Crafty.js A flexible framework for Javascript games, looks small maybe simple too.
  5. gameQuery Javascript game engine for jQuery, looks unmaintained and has a nice SteetFighter demo (unplayable) but hey, it’s jQuery.

We decided to write a tutorial about the game technology that we like to use, and so it's here. In this story, with PixiJS, a really simple and cool Javascript library, we'll start making a little shoot'em up game.

What we are going to do is make a spacecraft capable of moving and shooting, enemy waves and a beautiful animated background with moving clouds. The background will be focused on the first part (this story).

Are you ready?

Phase 1

Then let's start by setting up our project: well we've uploaded an already set code structure so we all work with the same base.

Download here the starter project

We'll need a local server to run the game: If you work with Windows or MAMP for macOS, I invite you to download WAMP, it's free and easy to use.

In index.html, we are importing the javascript files in the header:

<script src="../src/lib/pixi.min.js"></script>
<script src="../src/main.js"></script>

For every file we make, we have to do the same. The initialization of Pixi (based on the WebGL rendering engine), follows:

var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight);

We're telling the game to cover the entire browser window for this tutorial, so if you try now you'll get a black background.

The main.js file is where the whole game begins. It's like a manager with the game's first-run function and the loop where we can tell the game what to do on each frame. When the game starts, what we want is a blue sky background, so let's update the init function:

function init()  
     {      
      renderer.backgroundColor = 0x22A7F0;                  
      renderer.render(stage);      
      loop();  
     }

Pixi uses the hex color format, so you have to write your preceding 0x color code. Let's save your browser and see the final result!

Add a few more movements : clouds

Let's add some floating clouds.

First of all, in the src folder (which will create and move the clouds), let's add a new CloudManager class file:

class CloudManager  
{      
      constructor()      
      {      
      }      
      update()      
      {      
      }  
}

Don’t forget to add it in the index.html file as we did for main.js:

The constructor is the gateway where we can add the spawning function for our clouds. Basically, what we want is a a a method that can create a cloud every X seconds.

window.setInterval(function()  
{  
}  
, 1000);

This code, inserted in the constructor, will call every 1000 milliseconds (= 1 second) what is inside the moustache brackets.

Now let's add cloud graphics to the assets folder, and because it's better we have two different images: (the clouds in our case are white with a transparent background, you can find it on https://www.freepik.com)

We have to load the images before the game starts, so add them in the Pixi.loader.add function:

PIXI.loader.add([      
  "assets/cloud_1.png",      
  "assets/cloud_2.png"  
]).load(init);

Okay, we can now display the clouds in the CloudManager setInterval method:

window.setInterval(function()
{
    const sprite = (Math.random() > 0.5 ? "cloud_1" : "cloud_2");
    this.cloud = new PIXI.Sprite(PIXI.loader.resources["assets/" + sprite + ".png"].texture);
    this.cloud.anchor.set(0.5, 0.5);
    this.cloud.position.set(renderer.width * 1.2, renderer.height * Math.random());
    stage.addChild(this.cloud);
}
, 1000);

We practically did:

  • First, we calculate a random number between 0 and 1, and either it is less than 0.5 so we store the first cloud/sprite in a constant or it is the second cloud/sprite.
  • Then, with the image in the previous line, we create a new sprite object.
  • This sprite's origin will be its top left corner, so we're setting its anchor point in the middle.
  • We have to display the cloud beyond the right edge of the screen, so that it moves through the screen to the left: Renderer.width * 1.2 is the left edge + the width of the screen + 20% of its width. We can be sure we don't see it spawn. Renderer.height * Math.random) (is between 0 and the height of the window for the y position. The vertical position of the cloud will therefore be located between the top and bottom of the screen.
  • Finally, we addChild this cloud to the stage.

Nothing should appear if you run this code now, and it's purposeful because they have to pop out of sight. So we have to try and move them. The update function is where it should be done. But we need to store the clouds in an array for iteration and positioning.

Let's make a new array in the constructor of CloudManager:

this.cloudsList = [];

And let's push the clouds inside after the stage.addChild function:

this.cloudsList.push(this.cloud);

And now....it works!

Wait, something really should frustrate us: Where are all the clouds going? If we don't remove them after they leave the screen, they will continue to exist and some performance problems can occur. For each one that deletes them when their horizontal position is slightly lower than the left border of the screen (so we can't see them popping out):

if (element.position.x < -renderer.width * 0.3) {
    element.destroy();
    array.splice(0, 1);
}

What about a random change in the size of the cloud? Add this to the creation block for the cloud:

let minScale = 0.2;
let maxScale = 1.2;
let scale = Math.random() * (maxScale - minScale) + minScale;
this.cloud.scale.set(scale, scale);

And now...all you have to do is wait for the second part of the tutorial...:-)

Read the second part.

 

 

Background vector created by photoroyalty - www.freepik.com

 

 
by Janeth Kent Date: 17-02-2019 javascript video game course tutorial hits : 5570  
 
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

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…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

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