Explore Free Quintus Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Fri, 24 Feb 2023 21:14:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Quintus Tutorials – GameDev Academy https://gamedevacademy.org 32 32 How to Make an HTML5 Game https://gamedevacademy.org/how-to-make-a-html5-game/ Thu, 06 Jan 2022 09:30:39 +0000 https://gamedevacademy.org/?p=1585 Read more]]> Although Flash games have departed from this world, there is still a significant demand for browser-based and cross-platform games. Whether you yourself actively play them or not, more and more games from professional and indie developers alike come out each day.

This phenomenon is largely thanks to HTML5 games which have filled the gap to keep up with these eager gamers. In addition, thanks to the advancement of technology and new frameworks, HTML5 game development has reached extensive heights, allowing for multiplayer experiences, 3D graphics, and more! It is not unwise to say that gaming is now just as viable via a browser as it is on many other devices!

Assuming this sounds like an exciting prospect to you as a game developer, in this guide we’re going to delve into the topic of HTML5 game development and give you the run-down of how you can make your own games! Sit back, relax, and prepare to enhance your game development skills in entirely new ways!

What exactly is an HTML5 game?

Let’s start from total zero. What is HTML5? that’s a tricky question. There is an official definition of HTML5, which simply stands for the latest revision of HTML (the markup language used all over the world to build websites), and the more hyped definition (what most people understand when HTML5 is mentioned) which is all the “new” features of the web technologies that have come out in the last few years (JavaScript API’s like the Canvas or WebAudio, semantic HTML tags, etc).

For our purpose, we’ll use bits of the two. HTML5 is HTML in its latest version, which includes a whole bunch of cool features that make web technologies an open standard with endless possibilities combining HTML, CSS and JavaScript.

Having HTML along with all these superpowers that go beyond making a simple website allows us to make, among other things, games. These are HTML5 games.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

 Building blocks

The very basic building blocks of a HTML5 game are those of the web:

  • HTML
  • CSS
  • JavaScript

Similarly to what happens with HTML5, when people talk about CSS3 they usually refer to the new things that come with CSS’s latest specifications, but in an analog manner, CSS3 is simply the latest CSS. Ignoring for a second the semantics of these definitions and thinking of the hyped versions of these terms, we also may need, in order to make HTML5 games:

  • HTML5 (JavaScript API’s)
  • CSS3

With the above you can make awesome games that will run on modern web browsers on mobile and desktop, but some games might require more features, so there are more building blocks that you can add.

For instance, you may want to make 3D games. If that is the case there is also WebGL, which is a JavaScript API to render 2D and 3D graphics on the browser, using the GPU for greater performance.

Road crossing game made with HTML5

Server side

If you want your games to saved data remotely you’ll need a server-side for your game. You can develop your own backend using any server-side language, you’ll need well a server in this case.

  • JavaScript (NodeJS)
  • PHP
  • Java
  • Python
  • Ruby

Or you can use a third-party Backend-as-a-Service provider such as Firebase or Parse. Some have free versions you can use and they’ll start charging you once you surpass certain limits. Some of these providers are particularly focused on games, some are mostly conceived for mobile apps but can be used for games too.

How to distribute a HTML5 game

The easiest way to distribute a HTML5 is to simply put it out there! By being built as a website, you can just embed it in on a page and publish it. Just like that.

If you want to distribute it through proprietary platforms you have to go through a process called wrapping. Basically, you create a native app for the platform you wanna distribute it to (iOS, Android, etc) and put your game inside so that this app acts like a web browser and “runs” your game.

For desktop platforms such as Windows, Mac or Linux there is a tool called NWjs that allows you to pack your HTML5 games for these platforms.

We can only cover the basics here, but we encourage you to read our more in-depth advice about publishing games.

Match 3 game made with HTML5

HTML5 game frameworks

Most games share some concepts, that of sprites (graphic elements that represent enemies, players, elements in your game), scenes or stages, animations, sound, loading graphic assets, etc. Since most game developers want to focus on their actual game and not in creating this whole abstraction layer, it is recommended you use a HTML5 game frameworks.

HTML5 game frameworks and libraries that contain building components you can use to create your own games. These libraries are Open Source projects created and maintained by people who want to contribute to the HTML5 gamedev environment. In many cases they created the frameworks for their own games, and after realizing that other people would want to not only use it but also contribute to it they released them as Open Source code, so everybody wins.

Picking what game engine to use is an important decision, so make sure you do proper research before making your choice. No matter what engine you pick, you will have to get familiar with its code and inner working if you want to use properly, so they shouldn’t be treated as black boxes.

What can help you make your choice:

  • Is your game for desktop, mobile or both?
  • Do they have an active community?
  • Are there many people using the framework nowadays?
  • Is it being maintained or the Github page looks like an abandoned town?

Sometimes looking at real games gives you more insight than just words. This project compares different engines by making the exact same Breakout game in all of them.

Some popular free frameworks are:

Solar system project made with Babylon.js

HTML5 game development courses

Video courses are a great way to learn new technologies. The main difference between a video course and just watching YouTube videos is that there is more structure. Good courses have a clear goal and build on to it step by step. Below a list of courses and tutorials by Zenva that can give you the tools you need to create HTML5 games.

General Game Development

Phaser

WebGL, 3D, and XR

HTML5 Skills

At the GameDev Academy, as you know already we have a bunch of HTML5 game development tutorials, mostly on Phaser, LimeJs, Quintus and BabylonJS. There are other great places to find good quality HTML5 gamedev tuts:

HTML5 for Schools

Are you a teacher looking to help students get into frameworks like Phaser or teach them core and relevant web development skills? Try out Zenva Schools – an online platform offering coding-based courses for use in the classroom. The platform comes with video lessons, text summaries, quizzes, classroom management features, reporting, and more to help support learning HTML5!

HTML5 gamedev communities

You can find plenty of active communities on the Internet, some focus on gamedev in general and some others just in HTML5 gamedev.

Web:

Facebook:

Other Communities:

HTML5 gamedev challenges

  • The Global Game Jam® is an annual event, usually occurring in January every year. Participants work concurrently around the globe, and around a central theme, and then work together to create a game.
  • j13k competition: the competition is over but you can still read the Blog, subscribe to the Newsletter, and check the Resources for tools.

 HTML5 gamedev podcasts

I just know Lostcast, a podcast created by the guys from Lost Decade Games (whom we’ve interviewed in the past). In the podcast episodes they talk about they HTML5 games and game development in general.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Source Code – Quintus Educational Game Course https://gamedevacademy.org/source-code-quintus-educational-game-course/ Thu, 19 Nov 2015 08:07:02 +0000 https://gamedevacademy.org/?p=8419 Download the source code here.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Free Course – Intro to HTML5 Game Development https://gamedevacademy.org/intro-to-html5-game-development/ Thu, 03 Jul 2014 15:51:16 +0000 https://gamedevacademy.org/?p=2105 Read more]]> [button link=”https://academy.zenva.com/product/intro-to-html5-game-development/?zva_src=gamedevacademy” target=”_blank” style=”none, small, large, biglarge” title=”ACCESS THE COURSE FOR FREE”][/button]

Learn from scratch to create games that run on all platforms and devices!

In this online training you will learn the basics of HTML5 game development by creating your first Mario-style platformer game. All of it using 100% free tools and frameworks!

We’ll be using the Quintus HTML5 game framework, which is a lightweight yet powerful JavaScript library used to create professional 2D games. This course was created by Pablo Farias Navarro, HTML5 developer and founder of ZENVA.

What you’ll learn in this course:

  • Creating levels for your game using the Tiled open source map editor.
  • Loading assets in your game.
  • Making a 2D platformer game that runs on phones, tablets, smart tvs, computers and maybe even cars!
  • Understanding basic platformer mechanics.
  • Implementing enemies and their behaviors.
  • Putting it all together to create your first game!

Will I get a certificate after course completion?

Yes :)

Zenva Academy diploma

By completing any course at Zenva Academy you’ll be awarded with a completion diploma which can be verified via URL and exported to LinkedIn to boost your career and impress potential employers.

[button link=”https://academy.zenva.com/product/intro-to-html5-game-development/?zva_src=gamedevacademy” target=”_blank” style=”none, small, large, biglarge” title=”ACCESS THE COURSE FOR FREE”][/button]

]]>
Intro to HTML5 Mobile Game Development with Quintus https://gamedevacademy.org/intro-to-html5-mobile-game-development-with-quintus/ Wed, 04 Jun 2014 12:00:00 +0000 https://gamedevacademy.org/?p=1979 Read more]]>

Quintus is a lightweight JavaScript HTML5 game development framework created by Pascal Rettig. Making games with Quintus is really easy if you have basic JavaScript skills. The great thing about it is that your games will run on desktop, mobile phones, tablets, smart tvs and any HTML5 supporting device.

You can learn how to create your own cross-platform HTML5 games with Quintus in our online training courses:

HTML5 Mobile Game Development by Example – Educational Game

HTML5 Mobile Game Development by Example – Veggies vs Zombies

[button link=”http://academy.zenva.com/product/html5-game-development-by-example-educational-game/?zva_src=gamedevacademy” target=”_blank” style=”none, small, large, biglarge” title=”Link Title”][/button]

]]>
HTML5 Mobile Game Development by Example – Veggies vs Zombies [NEW] https://gamedevacademy.org/html5-mobile-game-development-by-example-veggies-vs-zombies-new/ Mon, 28 Apr 2014 21:34:09 +0000 https://gamedevacademy.org/?p=1991 Read more]]> Learn how to create games similar to the award winning Plants vs Zombies

What if you could use your HTML, CSS and JavaScript knowledge to create awesome mobile games for iOS, Android and the web?

In this course we’ll build an entire game called Veggies vs Zombies, defence game inspired in the popular game Plants vs Zombies. The game we’ll build doesn’t only cover all the game dev mechanics you need to know to fly free and make any game you want, but it’s also very addictive and fun to play!

Though out the course, we’ll use the lightweight and awesome game framework HTML5 Quintus, which allows you to make your own video games using only a text editor, a web browser and a local host.

What you’ll learn in this course:

  • Create a complete multilevel defence game
  • Basics of 2D games: sprites, scenes, stages.
  • Collision detection.
  • Making games that adjust to the screen resolution – a must in a post-pc world!
  • Loading levels from JSON files.
  • Adding audio to make your games memorable.
  • Putting it all together to make a fun and addictive gameplay!

This course was created by Pablo Farias Navarro, founder of ZENVA and the tech blogs GameDev Academy, HTML5 Hive and De Idea A App. Pablo specializes in web and mobile app development and has produced over 20 courses teaching over 35,000 students how to make games, apps and websites.

[button link=”https://academy.zenva.com/product/html5-mobile-game-development-by-example-veggies-vs-zombies/?zva_src=gamedevacademy” target=”_blank” style=”none, small, large, biglarge” title=”ACCESS THE COURSE AND START MAKING GAMES”][/button]

]]>
HTML5 Game Development by Example – Educational Game (NEW!) https://gamedevacademy.org/html5-game-development-by-example-educational-game-new/ Mon, 14 Apr 2014 20:33:51 +0000 https://gamedevacademy.org/?p=1976 Read more]]> What if you could turn that great game idea into a real game that could be played on the web, on desktop, iOS, Android and all other platforms?

Stop postponing your dreams and get started TODAY. Learn at your own pace how to create HTML5 games in this course that follows the learn by doing approach.

Through out the course, we’ll make an educational game with the Quintus HTML5 framework, one of the most powerful and lean game frameworks out there that allows you create games that work on phones, desktop, smart tvs and any HTML5 supporting devices!

These are just some of the many things you’ll learn in this course:

  • Creating simple 2D games for the web, mobile and all devices.
  • Working with modules to keep your code organized.
  • Creating 2D tile-based worlds.
  • Using sprites and spritesheets in your games.
  • Collision detection.
  • 2D physics basics.
  • Game flow: game over and restart game.
  • Loading level data from JSON objects.
  • Putting it all together in a simple demo!

This course was created by Pablo Farias Navarro, founder of ZENVA and active contributor to the Quintus open source project, the same library we use in this course.

After teaching over 30.000 people how to code games, apps and websites we’ve gained valuable insight on how online education should be.

We are putting it all in practice on this course and we are sure it will give you the tools you need to get your game ideas up and running.

]]>
How to Make a HTML5 PacMan with Quintus https://gamedevacademy.org/how-to-make-a-html5-pacman-with-quintus/ Tue, 24 Sep 2013 14:18:40 +0000 https://gamedevacademy.org/?p=1404 Read more]]> The following tutorial was created by Pascal Rettig (@cykod) and can be found in his site HTML5 Game Dev Tutorial, which will feature a collection of Quintus tutorials. If you’ve been following our Quintus tutorials such as the Math Racing Game or the Mario Clone series you’ll definitely enjoy this tutorial as well.

First a moment of reflection on the Genre: what is a Pac Man type game? The answer is that it’s a top-down action game. A player moves in fixed 2D board while enemies chase him in real-time.

Other top down action games include games like Bomberman and shooters like Ikari warriors (for those of you with a NES background)

Access the tutorial in HTML5 Game Dev Tutorial.

]]>
Adding Coins and Lives to the Mario-Style HTML5 Platformer https://gamedevacademy.org/adding-coins-and-lives-to-the-mario-style-html5-platformer/ Mon, 02 Sep 2013 12:52:36 +0000 https://gamedevacademy.org/?p=1178 Read more]]> NOTE: This tutorial is not updated to the latest Quintus version and doesn’t run with it.

This tutorial is the third part in the Mario HTML5 platformer series, so get ready to dig in deeper into the awesome Quintus game framework. In this tutorial we’ll learn how to add coins, lives to our player and how to show all of this in a “player stats” area.

Are you a French speaker? If so, thanks to Alexandre Bianchi you can enjoy an adapted French version of this tutorial.

Tutorial goals

  1. Implementing “lives” for our player.
  2. How to collect coins.
  3. Loading the coins location from a JSON object.
  4. Displaying a “player stats” area and keeping it updated.
  5. Searching for an object in a scene.

Get Another HTML5 Gamedev Shot

If you are enjoying this tutorial and want a lot more of this stuff feel free to check out our HTML5 game development online courses that cover all the basics to get started:

HTML5 Mobile Game Development for Beginners

Requirements

The requirements for the dodgy Mario clone tutorial series are:

  • Familiarity with HTML, CSS, JavaScript and basic object oriented concepts.
  • Clone or download Quintus from it’s Github page.
  • Setup a local webserver. We need to run the code in this tutorial in a web server and not by just double clicking on the files. WAMP for Windows, MAMP for Mac. On linux just type sudo apt-get install apache2.
  • Download and install the Tiled game editor, available for Linux, Mac and Windows
  • Have your favorite IDE ready (Netbeans, Eclipse, Sublime2, Notepad++, VIM, or any tool you use for coding).
  • Have your knuckles cracked and ready for a new dive into HTML5 gamedev.

Tutorial Assets

Get the full tutorial source code and images here. All images used in this tutorial have a Public Domain license.

Heads up!
I’ve provided the Quintus files among the tutorial source code but keep in mind that the framework is under heavy development. It’s be best if you just grab them straight from the Github page. Also, keep an eye on the repository as you work on your games since new features are being added.

Player Stats

In these series we’ve been working all along with just one scene: the level that contains the actual game. Quintus allows us to keep on many scenes on the screen so that for instance we can be scrolling through the level in one, but the other ones stay on their same place and don’t get scrolled.

Being more clear on this point, imagine we just use one scene, the level one, and we add player stats to it such as the number of lives and the number of coins. It’s all gonna look good until you start working and the viewport camera moves away from your initial location. The player stats will stay behind as the rest of the level. This concept is explored in more depth in our HTML5 Educational Game tutorial.

Anyway, let’s create a second scene called “gameStats”:

Q.scene("gameStats", function(stage) {
    var statsContainer = stage.insert(new Q.UI.Container({
        fill: "gray",
        x: 960/2,
        y: 620,
        border: 1,
        shadow: 3,
        shadowColor: "rgba(0,0,0,0.5)",
        w: 960,
        h: 40
        })
    );
        
    var lives = stage.insert(new Q.UI.Text({ 
            label: "Lives x 3",
            color: "white",
            x: -300,
            y: 0
        }),statsContainer);
    
    var coins = stage.insert(new Q.UI.Text({ 
            label: "Coins x 0",
            color: "white",
            x: 300,
            y: 0
        }),statsContainer);
});

What we are doing here is create a new scene that has a gray container which goes on the bottom of the page. This container has two Q.UI.Text objects, one for the lives and one for the coins. They both start with default values. In order to learn more about the Q.UI.Text and the containers check the file quintus_ui.js from the library and the HTML5 Educational Game tutorial.

Staging the game stats scene would be the last step. The asset loading should look like this (see that we are also adding a coin.png asset file, to be used next):

//load assets
Q.load("tiles_map.png, player.png, slime.png, fly.png, level1.tmx, coin.png", function() {            
    Q.sheet("tiles","tiles_map.png", { tilew: 70, tileh: 70});          
    Q.stageScene("level1");
    Q.stageScene("gameStats",1);
});

The second parameter when staging the scene is the index (0 by default). Scenes with higher index show on top of scenes with lower index.

Coins

Righto. All platformers need coins or something like them (diamonds, gold, fruits?). Their implementation using Quintus and the stuff we’ve learned so far is quite straightforward:

Q.Sprite.extend("Coin", {
    init: function(p) {
        this._super(p, {asset: "coin.png"});
    }            
});

We’ll load the coins in our level initialisation using a JSON object in a similar manner to how we did it with the enemies:

//level assets. format must be as shown: [[ClassName, params], .. ] 
            var levelAssets = [
                ["GroundEnemy", {x: 18*70, y: 6*70, asset: "slime.png"}],
                ["VerticalEnemy", {x: 800, y: 120, rangeY: 70, asset: "fly.png"}],
                ["VerticalEnemy", {x: 1080, y: 120, rangeY: 80, asset: "fly.png"}],
                ["GroundEnemy", {x: 6*70, y: 3*70, asset: "slime.png"}],
                ["GroundEnemy", {x: 8*70, y: 70, asset: "slime.png"}],
                ["GroundEnemy", {x: 18*70, y: 120, asset: "slime.png"}],
                ["GroundEnemy", {x: 12*70, y: 120, asset: "slime.png"}],
                ["Coin", {x: 300, y: 100}],
                ["Coin", {x: 360, y: 100}],
                ["Coin", {x: 420, y: 100}],
                ["Coin", {x: 480, y: 100}],
                ["Coin", {x: 800, y: 300}],
                ["Coin", {x: 860, y: 300}],
                ["Coin", {x: 920, y: 300}],
                ["Coin", {x: 980, y: 300}],
                ["Coin", {x: 1040, y: 300}],
                ["Coin", {x: 1100, y: 300}],
                ["Coin", {x: 1160, y: 300}],
                ["Coin", {x: 1250, y: 400}],
                ["Coin", {x: 1310, y: 400}],
                ["Coin", {x: 1370, y: 400}]
            ];
            
            //load level assets
            stage.loadAssets(levelAssets);              
Heads up!
It’s recommended you try to load all the entities in the game such as enemies, items, etc, using JSON objects. JSON is a data exchange protocol which is commonly used to receive and send information to and from the web. If your plan is to eventually load level data from the web or from the local storage it’s good that you keep JSON in mind and get used to working with this format.

Our level can be filled up with coins now but we still need to be able to grab them and keep a total of coins. Let’s update a bit our Player definition:

Q.Sprite.extend("Player",{
    init: function(p) {
        this._super(p, { asset: "player.png", x: 110, y: 50, jumpSpeed: -400, coins: 0});
        this.add("2d, platformerControls"); 

        this.on("hit.sprite",function(collision) {
            if(collision.obj.isA("Coin")) {
                collision.obj.destroy();
                this.p.coins++;
                //TODO: update the GUI
                
            }
        });
    },
    ...

This is firstly, setting an initial value of 0 coins. We are checking the collision with coin objects. If we find a coin then destroy the coin and increase the number of coins in 1. We still need to update the GUI, which we’ll be doing next.

Searching for the GUI

We grabbed a coin, destroyed it and increased our coin count. The GUI needs to be updated, but how do we find it? we need to search for it. Quintus has it’s own way of searching for objects:

this.on("hit.sprite",function(collision) {
    if(collision.obj.isA("Coin")) {
        collision.obj.destroy();
        this.p.coins++;
        var coinsLabel = Q("UI.Text",1).items[1];
        coinsLabel.p.label = 'Coins x '+this.p.coins;
        
    }
});

By doing

Q("UI.Text",1).items[1];

we are searching for all Q.UI.Text objects in the scene located at index 1. This returns an object, where the property “items” contains an Array with all the results. In this case the index 1 (second item in the Array) contains the text we are looking for. Index 0 of the array contains the lives text.

Once we find the text object we are looking for, we just update the label property (object.p.label, don’t forget the p which we always use to access an entity’s parameters in Quintus).

Player Lives

Our game so far is extremely tough. One strike and you are out! we’ll implement now player lives or energy. If the lives run out then we are getting the game over kick.

There are many ways in which lives / energy can be implemented. The way it’ll be in this example is:

  1. The player is hit by an enemy (same collision rules we have in place)
  2. The lives go minus one
  3. The player is “invincible” for 1 second, so that if you are hit again right away it won’t take a second life
  4. After the 1 second you can be hit again if you are not careful
  5. If the lives run out.. game over!

When the player is hit, ideally, the player sprite should be blinking for that second or have some sort of visual cue. Since this is just a tut not a real game we won’t show any visual cue.

Setup an initial number of 3 lives:

Q.Sprite.extend("Player",{
    init: function(p) {
        this._super(p, { asset: "player.png", x: 110, y: 50, jumpSpeed: -400, lives: 3, coins: 0});
        ...

Modify the enemies so that now they don’t kill you, but damage() you instead.

//component for common enemy behaviors
Q.component("commonEnemy", {
    added: function() {
        var entity = this.entity;
        entity.on("bump.left,bump.right,bump.bottom",function(collision) {
            if(collision.obj.isA("Player")) {                        
              collision.obj.damage();
            }
        });
        entity.on("bump.top",function(collision) {
            if(collision.obj.isA("Player")) { 
                //make the player jump
                collision.obj.p.vy = -100;
                
                //kill enemy
                this.destroy();
            }
        });
    },
    
});

The damage() method in the player will follow the steps mentioned before. It will make you invincible for 1 second and then you’ll be damageable again. We also need to update step() to keep track of this 1 second. The following goes inside Player:

step: function(dt) {
    if(Q.inputs["left"] && this.p.direction == "right") {
        this.p.flip = "x";
    } 
    if(Q.inputs["right"]  && this.p.direction == "left") {
        this.p.flip = false;                    
    }
    
    if(this.p.timeInvincible > 0) {
        this.p.timeInvincible = Math.max(this.p.timeInvincible - dt, 0);
    }
},
damage: function() {
    //only damage if not in "invincible" mode, otherwise beign next to an enemy takes all the lives inmediatly
    if(!this.p.timeInvincible) {
        this.p.lives--;
        
        //will be invincible for 1 second
        this.p.timeInvincible = 1;
        
        if(this.p.lives<0) {
            this.destroy();
            Q.stageScene("endGame",1, { label: "Game Over" }); 
        }
        else {
            var livesLabel = Q("UI.Text",1).first();
            livesLabel.p.label = "Lives x "+this.p.lives;
        }
    }
}

This part:

var livesLabel = Q("UI.Text",1).first();

is updating the GUI in a similar way to the coin counter, but using a first() method that the returned object comes with (remember that index 0 in the Array was the lives text).

This gives us a playable demo where you can collect coins, jump around, kill bad guys and if you are not careful they can take your lives away and kill you!

Congratulations

Congrats if you’ve got all the way here! you have now the basics of what can become a great game! Some ideas on what to build next:

  • Visual cue when the player is damaged
  • Multiple levels
  • Level boss
  • Grab extra lives
  • Enemies that take coins away instead of lives

What Else to Check Out

If you like my teaching style, at Zenva we have two high quality video courses on HTML5 game development where we build several examples of different types of games, such as a top-view shooting bad guys Zelda-style game, spaceship games, farming games, virtual pet games and many other examples!

HTML5 Mobile Game Development for Beginners

]]>
Adding Enemies to a HTML5 Mario-Style Platformer https://gamedevacademy.org/adding-enemies-to-a-html5-mario-style-platformer/ Mon, 26 Aug 2013 14:27:31 +0000 https://gamedevacademy.org/?p=1145 Read more]]> NOTE: This tutorial is not updated to the latest Quintus version and doesn’t run with it.

HTML5 Mario-Style Platformer Series with Quintus:

Are you a French speaker? If so, thanks to Alexandre Bianchi you can enjoy an adapted French version of this tutorial.

This tutorial is the second part of the Quintus Platformer Series. In the first tutorial we learned some framework basics, build a basic level using the Tiled map editor, loaded the level in our game and implemented a Player class which we can control using the keyboard and move around the level.

In this second tutorial we’ll add enemies to the level. We’ll implement two types of enemies: “ground enemies” and “vertical enemies”. We’ll also cover how we can have our enemies scan the environment around them and act accordingly.

Tutorial goals

  1. Creating creatures that follow simple movement and behavior rules
  2. Using collision detection to kill the player or the enemies
  3. Understanding the game loop step() method
  4. Learn how to create reusable components
  5. Having enemies “observe” around them and act accordingly
  6. Loading level elements from a JSON object

HTML5 game dev, I like that!

If you are enjoying this tutorial and want a lot more of this stuff feel free to check out our HTML5 game development online courses that cover all the basics to get started:

HTML5 Mobile Game Development for Beginners

Requirements

As I mentioned in the introduction, you should have completed the previous Quintus tutorial. The requirements for these tutorial series are:

  • Familiarity with HTML, CSS, JavaScript and basic object oriented concepts.
  • Clone or download Quintus from it’s Github page.
  • Setup a local webserver. We need to run the code in this tutorial in a web server and not by just double clicking on the files. WAMP for Windows, MAMP for Mac. On linux just type sudo apt-get install apache2.
  • Download and install the Tiled game editor, available for Linux, Mac and Windows
  • Have your favorite IDE ready (Netbeans, Eclipse, Sublime2, Notepad++, VIM, or any tool you use for coding).
  • Have your knuckles cracked and ready for coding.

Tutorial Assets

Get the full tutorial source code and images here. All images used in this tutorial have a Public Domain license.

Heads up!
I’ve provided the Quintus files among the tutorial source code but keep in mind that the framework is under heavy development. It’s be best if you just grab them straight from the Github page. Also, keep an eye on the repository as you work on your games since new features are being added.

Killer Flies

We’ll begin by creating a new class which inherits from Q.Sprite. VerticalEnemies as I’ve called them will be alien flies that only move up and down. You can step on them to kill them and if you touch them in any other manner they’ll kill you.

The vertical movement will be within a range. We’ll call the distance they’ll move from their initial location “rangeY”. So if I define rangeY = 100 it means they will move 100 pixels up from the start, then down until they go 100 pixels from the initial location.

//enemy that goes up and down
Q.Sprite.extend("VerticalEnemy", {
    init: function(p) {
        this._super(p, {vy: -100, rangeY: 200, gravity: 0 });
        this.add("2d");
        
        this.p.initialY = this.p.y;
        
        //TODO: check for player collisions, die or kill accordingly
    },
    step: function(dt) {                
        //TODO: update range movement within the game loop
    }
});

Let’s analise this step by step. We define our class and give it a default rangeY of 200 pixels. We’ve also set gravity to 0 which means they won’t fall to the ground but will float instead (the gravity is given by the 2d component, which we still need for easier collision detection). The parameter initialY will store the initial location in the Y axis, which we’ll use in our calculations.

The step() will be executed multiple times per second and will be used to check things that “should be being checked all the time”. This is what we call the Game Loop, an important concept in game development. The parameter dt represents the amount of time in seconds that has passed since the step() method was last called.

Let’s add the code inside step() to check that we are moving within our range, and to switch directions once we reach the borders of this range:

step: function(dt) {                
    if(this.p.y - this.p.initialY >= this.p.rangeY && this.p.vy > 0) {
        this.p.vy = -this.p.vy;
    } 
    else if(-this.p.y + this.p.initialY >= this.p.rangeY && this.p.vy < 0) {
        this.p.vy = -this.p.vy;
    } 
}

In Quintus and when using the CANVAS tag (and in all other game frameworks that I’m familiar with for the matter) the Y axis starts in zero at the top and is positive when going down. The X axis is zero on the left as usual.

If we reached the bottom of the range while moving up (vy is our speed in Y, which is positive when going down) then we should change direction (setting vy to -vy). Same applies for when going up.

So that’s how we can use step() to check for things on every game iteration. Start thinking of all the possibilities this opens and how powerful it is. In the game loop you can check and update pretty much everything. Actually that is how the framework works behind the scenes! if you open up quintus_2d.js you’ll find step() being used for collision detection, movement, etc.

Heads up!
Spend at least half an hour looking at the code of the Quintus library. Don’t just grab stuff from the examples you find on the web. You need to spend time looking at how the inners of the framework work. You’ll be surprised on how intuitive and simple it is.

So what if you touch the flies? we’ll, it depends on WHERE you touch them (and yes, we are still talking about game development here). If you step on them, you kill them (pure Mario style). If you hit them on either side or on the bottom then you die. Let’s add the remaining code:

init: function(p) {
    this._super(p, {vy: -100, rangeY: 200, gravity: 0 });
    this.add("2d");
    
    this.p.initialY = this.p.y;
    
    this.on("bump.left,bump.right,bump.bottom",function(collision) {
        if(collision.obj.isA("Player")) { 
          Q.stageScene("endGame",1, { label: "Game Over" }); 
          collision.obj.destroy();
        }
    });
    this.on("bump.top",function(collision) {
        if(collision.obj.isA("Player")) { 
          collision.obj.p.vy = -100;
          this.destroy();
        }
    });
},

With this.on we are listening for events. Events are a core elements in the Quintus framework and this is how you can listen for them. You’ll find the definition of the bump.* events inside quintus_2d.js.

When the collision is triggered, we can check the class of element we have collided with using collision.obj.isA(…).

If the player hits the enemy in all sides except top a “game over” scene will be staged (we still need to create it) and the player object destroyed.

If we step on the enemies, the player gets a little bounce back and the enemy is destroyed.

Game Over Scene

In the next tutorial we’ll implement player lives. For now the game will be tough, if you die once the game is over. And for simplicity we are just gonna reload the page on game over. Add the following scene staging code:

Q.scene("endGame",function(stage) {
    alert("game over");
    window.location = "";
});

Showing the Enemies

Inside the level1 initialisation you can create enemies in the same way we’ve created the player:

stage.insert(new Q.VerticalEnemy({x: 800, y: 120, rangeY: 70, asset: "fly.png" }));

You should be able to create, kill and be killed by flies now.

flies

Juicy slimes

The second type of enemy we’ll be adding here are creatures that move on the ground level (I called them GroundEnemies). If they hit a hall or the edge of a cliff they turn on their back and move on the other direction (flipping the sprite as well to face likewise).

//enemy that walks around          
 Q.Sprite.extend("GroundEnemy", {
    init: function(p) {
        this._super(p, {vx: -100, defaultDirection: "left"});
        this.add("2d, aiBounce");
        
        this.on("bump.left,bump.right,bump.bottom",function(collision) {
            if(collision.obj.isA("Player")) { 
              Q.stageScene("endGame",1, { label: "Game Over" }); 
              collision.obj.destroy();
            }
        });
        this.on("bump.top",function(collision) {
            if(collision.obj.isA("Player")) { 
                //make the player jump
                collision.obj.p.vy = -300;
                
                //kill enemy
                this.destroy();
            }
        });
    },
    step: function(dt) {
        //TODO for edges and turn back when finding them
    }
});

What we added above is pretty much the same we added for the VerticalEnemy, with the sole difference that we included the component “aiBounce” which gives the enemies some basic behaviour: walking and turning around when hitting walls. I strongly recommend you take a look at this component in quintus_2d.js as it’ll give you more hints on how to create your own.

Since we are duplicating code it’s best to create a reusable component called “commonEnemy” and update the code a bit:

//component for common enemy behaviors
Q.component("commonEnemy", {
    added: function() {
        var entity = this.entity;
        entity.on("bump.left,bump.right,bump.bottom",function(collision) {
            if(collision.obj.isA("Player")) {                        
              Q.stageScene("endGame",1, { label: "Game Over" }); 
              collision.obj.destroy();
            }
        });
        entity.on("bump.top",function(collision) {
            if(collision.obj.isA("Player")) { 
                //make the player jump
                collision.obj.p.vy = -100;
                
                //kill enemy
                this.destroy();
            }
        });
    },
    
});

//enemy that walks around          
Q.Sprite.extend("GroundEnemy", {
    init: function(p) {
        this._super(p, {vx: -100, defaultDirection: "left"});
        this.add("2d, aiBounce, commonEnemy");                
    },
    step: function(dt) {        
        //TODO
    }
});

//enemy that goes up and down
Q.Sprite.extend("VerticalEnemy", {
    init: function(p) {
        this._super(p, {vy: -100, rangeY: 200, gravity: 0 });
        this.add("2d, commonEnemy");                
        this.p.initialY = this.p.y;
    },
    step: function(dt) {                
        if(this.p.y - this.p.initialY >= this.p.rangeY && this.p.vy > 0) {
            this.p.vy = -this.p.vy;
        } 
        else if(-this.p.y + this.p.initialY >= this.p.rangeY && this.p.vy < 0) {
            this.p.vy = -this.p.vy;
        } 
    }
});

The “added()” method inside the component creation is executed once the component is loaded to the object. See how inside this method we obtain the enemy by getting this.entity, after which you can pretty much refer to the enemy as if you were in it’s own init() method.

Scanning the Environment

If you noticed in the previous code I’ve left the step() method of the GroundEnemy. We’ll use the game loop to check for edges, otherwise our enemies will fall down the cliff.

This feature might become soon a part of the aiBounce component.

Before giving up the code I want to explain what we are trying to do:

  • We want, in every step, to check the tiles beneath and in front of our monster, and read whatever we find there.
  • If there is just another tile, keep walking.
  • If there are no tiles it means we are reaching the edge. In this case turn back and walk to the opposite direction
  • This is a very rudimentary AI feature, we are giving our slime some basic perception of the world around it
  • Quintus makes this easy by using the locate() method. We specify the current stage, the coordinates and the collision type and it gives us whatever is found there
step: function(dt) {        
    var dirX = this.p.vx/Math.abs(this.p.vx);
    var ground = Q.stage().locate(this.p.x, this.p.y + this.p.h/2 + 1, Q.SPRITE_DEFAULT);
    var nextTile = Q.stage().locate(this.p.x + dirX * this.p.w/2 + dirX, this.p.y + this.p.h/2 + 1, Q.SPRITE_DEFAULT);
    
    //if we are on ground and there is a cliff
    if(!nextTile && ground) {
        if(this.p.vx > 0) {
            if(this.p.defaultDirection == "right") {
                this.p.flip = "x";
            }
            else {
                this.p.flip = false;
            }
        }
        else {
            if(this.p.defaultDirection == "left") {
                this.p.flip = "x";
            }
            else {
                this.p.flip = false;
            }
        }
        this.p.vx = -this.p.vx;
    }
}

Enemies in JSON

Scalability (the ability to grow without going crazy) is an aspect to keep in mind. We wanna be able to quickly create multiple enemies and not having to create the individual instances one by one.

Also, there is the chance that we may want to load the level parameters from the Internet, in which case we need to be able to load stuff from a JSON object.

I’m just gonna show a quick way to load the level enemies using JSON. You could load a lot of other parameters in this manner, and this JSON object could come from the Internet, the local storage, etc. The following code goes inside our level1 initialisation, and uses a Quintus method that stages have called “loadAssets”:

//level assets. format must be as shown: [[ClassName, params], .. ] 
            var levelAssets = [
                ["GroundEnemy", {x: 18*70, y: 6*70, asset: "slime.png"}],
                ["VerticalEnemy", {x: 800, y: 120, rangeY: 70, asset: "fly.png"}],
                ["VerticalEnemy", {x: 1080, y: 120, rangeY: 80, asset: "fly.png"}],
                ["GroundEnemy", {x: 6*70, y: 3*70, asset: "slime.png"}],
                ["GroundEnemy", {x: 8*70, y: 70, asset: "slime.png"}],
                ["GroundEnemy", {x: 18*70, y: 120, asset: "slime.png"}],
                ["GroundEnemy", {x: 12*70, y: 120, asset: "slime.png"}]
            ];
            
            //load level assets
            stage.loadAssets(levelAssets); 

Suggested Activities

We’ve reached the end of this tutorial and before closing this up I’d like to suggest a few activities you can try on your own:

  • Join and participate of the vibrant Quintus Google Plus community
  • Add more kinds of enemies
  • Load the enemies JSON and level TMX files from a remote location.
  • Share back to the community the reusable components you’ve created.

What Else to Check Out

If you like my teaching style, at Zenva we have two high quality video courses on HTML5 game development where we build several examples of different types of games, such as a top-view shooting bad guys Zelda-style game, spaceship games, farming games, virtual pet games and many other examples!

HTML5 Mobile Game Development for Beginners

]]>
Create a HTML5 Mario-Style Platformer Game https://gamedevacademy.org/create-a-html5-mario-style-platformer-game/ Mon, 19 Aug 2013 12:44:09 +0000 https://gamedevacademy.org/?p=1014 Read more]]> NOTE: This tutorial is not updated to the latest Quintus version and doesn’t run with it.

HTML5 Mario-Style Platformer Series with Quintus:

Are you a French speaker? If so, thanks to Alexandre Bianchi you can enjoy an adapted French version of this tutorial.

Among all game styles, platformers have stood out for decades and have proved to be a simply fun to play array of characters, blocks, tubes and monsters. In this tutorial we’ll create a simple Mario-style platformer using the Quintus HTML5 game framework, which allows you to speed up the construction of a simple and playable prototype.

This will be a three part series. In this first part, we’ll focus on constructing the level using the Tiled map editor, loading the level into the game and setting up the platform type of game (basically a character that runs and jumps around a scrollable level). In the second part of the series we’ll add enemies with different behaviours. The third tutorial will have coins and lives for the player.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

The Requirements

We’ll be using the Quintus game development framework on this tutorial. This Open Source framework was created by Pascal Retig and is aimed for the creation of video games with JavaScript for mobile, desktop and beyond.

Starting points to get familiar with Quintus are the official guide, the G+ community and my previous Quintus tutorial.

  • Familiarity with HTML, CSS, JavaScript and basic object oriented concepts.
  • Clone or download Quintus from it’s Github page.
  • Setup a local webserver. We need to run the code in this tutorial in a web server and not by just double clicking on the files. More on that later. WAMP for Windows, MAMP for Mac. On linux just type sudo apt-get install apache2.
  • Download and install the Tiled game editor, available for Linux, Mac and Windows
  • Have your favorite IDE ready (Netbeans, Eclipse, Sublime2, Notepad++, VIM, or any tool you use for coding).
  • Download the source code here.
  • Crack your knuckles and start coding!

The Setup

Create a new folder in your web server public folder (www folder in most cases), let’s call this new folder “zenvaplatformer”. In it, create the following sub-folders and empty files, and copy the JS files contained in Quintus/lib where shown:

zenvaplatformer/index.html
zenvaplatformer/data/
zenvaplatformer/lib/ —> copy the Quintus/lib JS files here
zenvaplatformer/images/

Heads up!
When working with Quintus, as well as other libraries from Github, it’s always good to keep an eye on the repo page as new features are constantly being added. You don’t wanna stay behind with an old version of the library. In the case of Quintus a lot of work is being done at the moment so keep an eye for new features and API changes!

After downloading the files from here. I’d recommend you do not look at the code unless you wanna ruin the fun of coding along. What you will need to do though is copy the game assets from /data and /images to their corresponding project folders.

The Map

All games, and in particular platformer games take place in a virtual world. In our case it’ll be a 2D, tile-based world. Tile-based means that the world is composed of individual “tiles” or blocks. Think of old NES games, how you could just find block patters that repeated themselves. Well that’s what we are building here too.

In order to create this 2D, tile-based world we’ll use the Tiled game editor. The Quintus engine has support for TMX file loading, which is one of the formats that can be produced by Tiled.

The map for this example is ready and waiting for you in the /data folder, but I still want to guide you through the process of a basic map creation:

1. Open Tiled and create a new map. In the dialog box you have to specify the size of the map in terms of how many tiles or blocks it will have for width and height. You also specify here the size of the tile in pixels. In our example the width of the map is 40 tiles, the hight 10 tiles, and we’ll be working with tiles of 70×70 pixels.

2. Now where do we get the tiles from? we need what’s called a spritesheet or tileset, which is the name given to image files that contain all the tiles/sprites of the game. You can get plenty of free spritesheet at OpenGameArt.org, just read carefully the license of the images and give the author proper attribution in case they are Creative Commons. If they are Public Domain you can just use them without restriction.

But hey you just downloaded the example files so we do have a spritesheet to have a play with. Go to Map -> New Tile, then “Browse” and look for the file /images/tiles_map.png. Make sure you set the tile dimensions correctly (70×70), also there the margin, spacing and offsets should be 0.

With the current version of Quintus, you can’t use spritesheets that have spacings or margins. Also, the first block in the spritesheet (from left to right) will not be shown so leave that blank as I have done in the example file.

tiled adding tileset

3. Having loaded the tileset we can now “paint” a map using the buttons on the menu. In the platformer example we’ll have two layers, one to hold the collision elements (the elements that will block the player’s path, or sustain him as a ground) and a background layer for just decoration. Create a new layer using the icon with the “+” under the layer’s area. Give them both names to distinguish them. NOW you can start painting your map.

tiled map editor

4. If we want to have our files loaded with Quintus we need to save them in non-compressed XML format (tmx extension). Go to “Preferences”, then click on the “General” tab, where it says “Store tile layer data as” make sure XML is selected. Now you can save your map and this type of TMX maps are the ones you can use in your HTML5 games.

The Quintus Setup and Asset Loading

Copy the following contents to your index.html file:

    
        
        
        
    
        
            var Q = Quintus()
                .include("Sprites, Scenes, Input, 2D, Touch, UI")
                .setup({
                    width: 960,
                    height: 640
                }).controls().touch();          
        
    

What we are doing here is basically setting up the Quintus object with the modules that we’ll use, activating the touch screen and platform controls. For a description of what each module does check out the official guide and also in my previous Quintus tutorial I’ve gone through the basics of the framework.

The next step is to load our game assets and to initiate and show our first level. An important concept in Quintus is that of “stages” which can be understood as “layers” that go on top of each other. Scenes are instructions that are “executed” in a stage. For example I have two stages (layers), I put one scene that loads the level in one stage and I put another scene that shows the game score in the other stage (that goes on top of the first one). In this example we’ll just have one stage which is where the level is loaded.

//load assets
Q.load("tiles_map.png, player.png, level1.tmx", function() {
  Q.sheet("tiles","tiles_map.png", { tilew: 70, tileh: 70});          
  Q.stageScene("level1");
});

See how we load the images, then we create a sprite sheet for the tileset of the map. When you do so don’t forget to specify the dimensions of the tiles.

The Level

We’ve put on stage a scene called “level1”. We need now to initiate this scene. This is where we’ll load the game background and collision layers from the TMX file that came with the example (you could also load your own map here).

Q.scene("level1",function(stage) {          
    var background = new Q.TileLayer({ dataAsset: 'level1.tmx', layerIndex: 0, sheet: 'tiles', tileW: 70, tileH: 70, type: Q.SPRITE_NONE });
    stage.insert(background);   
    stage.collisionLayer(new Q.TileLayer({ dataAsset: 'level1.tmx', layerIndex:1,  sheet: 'tiles', tileW: 70, tileH: 70 }));      
});

We are creating two Q.TileLayer objects here. One will be used for the background and one for the collision layer. See how we make reference to the TMX file and the layerIndex, which is the order of the layer in the Tiled map (you can also open the TMX file in a text editor to figure out which layer goes where). Important as well to make explicit the tile dimensions here.

For the background we are using type: Q.SPRITE_NONE which means it will be ignored by the player when it comes to collision detection. Collision and how it works is explained in depth in my previous Quintus tutorial.

You should be seeing part of the game map now in your browser.

The Player

The last bit we’ll be looking at in this first part of the tutorial series will be how to add the player and make it a “platformer” player. Firstly, we need to create a class for the player. Add the following after the Quintus initiation code:

Q.Sprite.extend("Player",{
    init: function(p) {
      this._super(p, { asset: "player.png", x: 110, y: 50, jumpSpeed: -380});
      this.add('2d, platformerControls');              
    },
    step: function(dt) {
        if(Q.inputs['left'] && this.p.direction == 'right') {
            this.p.flip = 'x';
        } 
        if(Q.inputs['right']  && this.p.direction == 'left') {
            this.p.flip = false;                    
        }
    }                    
  });

Quintus has it’s own class and inheritance system and what we are doing here is creating a subclass of Q.Sprite called Q.Player. The constructor begins by running the parent’s constructor with some parameters: the player image file, the initial location (x,y) in the map, and jumpSpeed, which overrides the default jumpSpeed given by the component “platformerControls”, which is the concept I’m heading onto next.

Objects can have components added, which is basically adding a set of methods and properties. We are adding the 2d component, which provides basic physics (speed, acceleration, gravity) and collision detection. We are also adding the platformerControls component which makes the player movable with the keyboard (and touch screen as well since we run touch() when initiating the Q object.

The second method in Player, step(), is our door to the game loop. In most games there is something called a “game loop”, which refers to a set of instructions that are executed very often (many times per second) and allow the game to check for different states and modify variables accordingly.

All sprites in Quintus can have a step() method added. What we check here will be checked on the game loop. In our case we check the user input and flip our sprite accordingly, so that it faces the direction it walks to.

Time to Play

As you might have guessed, the last step towards having a player we can control is to actually place it in the level, for which we need to add the following in the scene initialisation:

var player = stage.insert(new Q.Player());
stage.add("viewport").follow(player,{x: true, y: true},{minX: 0, maxX: background.p.w, minY: 0, maxY: background.p.h});

The viewport will add a “camera” that will follow the player through the level as we are used to seeing. This camera will follow the player on x and y (the second parameter) and it will be restricted to the level area, so that we can’t show spaces outside of this level. You could restrict the camera to any area you want as long as you provide the coordinates in this optional parameter.

Righto, now we have a fully playable platformer demo. There are no enemies yet though, but don’t worry, that’s what we’ll be adding in the next tutorial in this series.

The Files

Download this tut’s source code here.

What Else to Check Out

At Zenva we have two high quality video courses on HTML5 game development that cover the entire process of making a game with HTML5.

HTML5 Mobile Game Development for Beginners

]]>