Skip to main content

Building a Game using JavaScript : Part-1


I really wanted to write a tutorial about a game technology I like to use, so here it is. In this story, we will start making a little shoot’em up game with PixiJS, a really simple and cool Javascript library.
What we are going to do exactly is to make a spaceship able to move and shoot, enemy waves coming through and a beautiful animated background with moving clouds. The first part (this story) will focus on the background.
Ready guys? Let’s nail it!

Getting started

Let’s start by setting up our project: I uploaded a code structure already set so we are all working with the same base. However if you want to make it yourself, I put a picture of my folder just below:
Project folder structure
We will need a local server to run the game: I invite you to download WAMP if you’re working with Windows, or MAMP for macOS, they are free and easy to use. Let’s put your game folder in the server one (htdocs for MAMP / www for WAMP) and type the localhost link in your favorite browser (for me: http://localhost:8888/Spaceship/bin/)
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>

… and we need to do the same for every file we make. Then comes the initialization of Pixi (which is based on the WebGL render engine):

var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight);
For this tutorial, we tell the game to cover the whole browser window, so if you try it now you will get an all-black background.
The main.js file is the place where all the game starts. It’s like a manager, with the first-executed function of the game, and the loop where we can tell the game what it needs to do on each frame. What we want is a blue background for the sky when the game starts, so let’s update the init function:

function init()
    renderer.backgroundColor = 0x22A7F0;

Pixi is using the hex color format, so you need to write your color code preceded by 0x. Let’s save and see the result in your browser!

Clouds everywhere

This background is very boring, let’s add some floating clouds.

First, let’s add a new CloudManager class file in the src folder (which is going to create and move the clouds):

class CloudManager

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

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

The constructor is the entry point of this class where we can add the spawn function for our clouds. What we want is basically a method able to create a cloud every X seconds, and it’s fine because there is a javascript thing for this:

, 1000);

This piece of code, placed in the constructor, will call what’s inside the moustache brackets every 1000 milliseconds (= 1 second).
Let’s add cloud sprites in the assets folder, and because it’s better we have 2 different images: (the clouds are white with transparent background so they were invisible on this page, but here are the links on GitHub ;)
We need to load the sprites before the game starts, so add them in the Pixi.loader.add function:


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

    const sprite = (Math.random() > 0.5 ? "cloud_1" : "cloud_2"); = new PIXI.Sprite(PIXI.loader.resources["assets/" + sprite + ".png"].texture);, 0.5); * 1.2, renderer.height * Math.random());
, 1000);

To resume this code:
  • First, we are computing a random number between 0 and 1, and either it’s less than 0.5 so we store the first sprite in a constant or otherwise it’s the second one.
  • Then, we create a new sprite object with the image we got in the previous line.
  • The origin point of this sprite is going to be its top left corner, so we set its anchor point in the middle.
  • We have to display the cloud beyond the right border of the screen, so it can move to the left through the screen: renderer.width * 1.2 is the left border position + the width of the screen + 20% of its width. We can be sure that we won’t see it spawning. For the y position, renderer.height * Math.random() is a number between 0 and the window height. So the cloud vertical position will be located between the top and the bottom of the screen.
  • Finally, we addChild this cloud to the stage.
If you run this code, nothing should appear, and it’s on purpose because they have to pop out of sight. So now we have to make them move.
The update function is the place to do it. But we need to store the clouds in an array so we can iterate through and set their positions. Let’s initialize a new array in CloudManager constructor:

this.cloudsList = [];

… and push the clouds inside after the stage.addChild function:


Now we can iterate the array in update and set the position of each cloud:

this.cloudsList.forEach(function(element) {
    element.position.x -= 4;

Now it’s working!
Moving clouds!

Oh wait, something should actually annoy us: where are all those clouds going?

Yeah, if we don’t remove them after they left the screen, they will continue to exist and it may cause some performance troubles. Let’s add a statement in forEach that delete them when their horizontal position is a little bit inferior to the left border of the screen (so we can’t see them popping out):
We’re done with the clouds!
What about making a random variation on the clouds size? Add this to the cloud creation block:

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

Random clouds size
If you something’s missing / not working in your code, you can check the result here.

Thank you for reading!

If you want to build a website just like Trivago and Tripadvisor then try our Hotel price comparison API, which compares more than 200 websites to generate JSON results .


  1. Thanks for sharing with us your wisdom.This will absolutely going to help me in my projects .

    Cloud Computing Classes in Chennai

    Cloud Computing Institutes in Chennai

    1. Great Article. Thank you for sharing! Really an awesome post for every one.

      IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

      JavaScript Training in Chennai

      JavaScript Training in Chennai

  2. This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
    WordPress development company in Chennai

  3. in this content i got a lot information about that javascript thanks for a helpful information and its assist for me to study..once again thanks for useful information
    Javascript Classes in Bangalore
    Advanced Javascript Training in Bangalore
    Best Institute for Javascript in Bangalore
    Javascript Course in Bangalore
    Javascript Training Courses in Bangalore

  4. in this content i got a lot information about that javascript thanks for a helpful information and its assist for me to study..once again thanks for useful information
    Javascript Classes in Bangalore
    Advanced Javascript Training in Bangalore
    Best Institute for Javascript in Bangalore
    Javascript Course in Bangalore
    Javascript Training Courses in Bangalore

  5. This comment has been removed by the author.

  6. Thank you for excellent article.You made an article that is interesting.
    Best AWS certification training courses. Build your AWS cloud skills with expert instructor- led classes. Live projects, Hands-on training,24/7 support.

  7. I have been reading for the past two days about your blogs and topics, still on fetching! Wondering about your words on each line was massively effective. Techno-based information has been fetched in each of your topics. Sure it will enhance and fill the queries of the public needs. Feeling so glad about your article. Thanks…!
    best software testing training in chennai
    best software testing training institute in chennai with placement
    software testing training

    software testing training and placement
    software testing training online
    software testing class
    software testing classes in chennai
    best software testing courses in chennai
    automation testing courses in chennai

  8. Nice is really interesting to read this article...Find latest Sarkari Job for freshers & experienced graduates across India & get free Naukri/Job alerts on recent & upcoming Sarkari jobs vacancies through Sarkari Job, as a jobs source we provides present and latest recruitment details for all Government/Sarkari Naukri across India.

  9. more about the blog is good but if you was seen any other blog the content should be failed to fulfill the users requests on that field,but in this blog the content will fulfill the users who related to search this field.... thanks a for ur efforts
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

  10. Thanks for sharing this, I actually appreciate you taking the time to share with everybody.
    Data Science Course In Hyderabad With Placements

  11. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    java online training

  12. Good and valuable information, this information is so useful and informative which you have shared here. It is very knowledgeable information and beneficial for beginners to develop their knowledge. Thanks for sharing it. Computer Programming Courses Online In Myanmar

  13. Thank you for sharing your knowledge and experience. I really appreciate the author's efforts in writing these high quality educational articles. Glad to discover this blog, great blog. Full stack developer course in Chennai

  14. Informative and useful article with step by step explanation. Thanks for sharing Angular training in Chennai

  15. Awesome informative blog, very good information thanks for sharing such wonderful blog with us, after long time came across such knowledgeable blog. keep sharing such informative blog with us.
    DevOps Training in Hyderabad
    DevOps Course in Hyderabad

  16. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data scientist course in delhi

  17. I truly appreciate just perusing the entirety of your weblogs. Just needed to educate you that you have individuals like me who value your work. Unquestionably an extraordinary post. Caps off to you! The data that you have given is exceptionally science training in chennai

  18. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.
    data scientist training in malaysia


Post a Comment

Popular posts from this blog

30 Amazing Machine Learning Projects for the Past Year (v.2018)

For the past year , we’ve compared nearly 8,800 open source Machine Learning projects to pick Top 30 (0.3% chance). This is an extremely competitive list and it carefully picks the best open source Machine Learning libraries, datasets and apps published between January and December 2017. Mybridge AI evaluates the quality by considering popularity, engagement and recency. To give you an idea about the quality, the average number of Github stars is 3,558. Do visit our Hotel price comparison api which compares more than 200 hotel websites to get you the best possible price of your dream hotel. Python Projects of the Year (avg. 3,707 ⭐️): Here (0 duplicate) Learn Machine Learning from Top Articles for the Past Year: Here (0 duplicate) Open source projects can be useful for data scientists. You can learn by reading the source code and build something on top of the existing projects. Give a plenty of time to play around with Machine Learning projects you may

Cheat Sheets for AI, Neural Networks, Machine Learning, Deep Learning & Big Data

Over the past few months, I have been collecting AI cheat sheets. From time to time I share them with friends and colleagues and recently I have been getting asked a lot, so I decided to organize and share the entire collection. To make things more interesting and give context, I added descriptions and/or excerpts for each major topic. This is the most complete list and the Big-O is at the very end, enjoy… If you like this list, you can let me know  here Neural Networks Neural Networks Cheat Sheet Neural Networks Graphs Neural Networks Graphs Cheat Sheet Neural Network Cheat Sheet Ultimate Guide to Leveraging NLP & Machine Learning for your Chatbot Code Snippets and Github Included Machine Learning Overview Machine Learning Cheat Sheet Machine Learning: Scikit-learn algorithm This machine learning cheat sheet will help you find the right estimator for the job which is the most difficult part. Th