JavaScript / HTML5 Game Development – How To Create Games

  Game Development

If you are a gamer (like most people), you probably thought of making your own video game or at least wonder how video games are developed.

Video games are made to entertain people, like you and me.

To be able to create a video game, you must understand first the purpose of your development and how knowledgeable you are when it comes to programming.

Of course, game development is not for everyone. If you are a programmer and you only develop software, sometimes you will feel like you are out of your zone.

 

person using laptop computers

Game development offers a TON of work and responsibilities. To be able to create an amazing game, you would need to understand how to design a game, how to program the game, how to write music and etc. These things form the actual game. Without one of these (let’s say music), the game would feel… empty… or… boring.

As a game developer, it is your responsibility to entertain gamers. To make them feel emotions that you want them to feel.

In this article, we’ll be guiding you on how to develop a video game using JavaScript and HTML5. If you don’t have any knowledge about vanilla JavaScript and HTML5, then this course is perfect for you as we’ll explain to you every part of game development that you need to know.

Although if you’re already a game developer yourself, then, you have the advantage to understand what’s going on.

But first…

What is a video game?

A video game is a digital game designed mainly for personal computers. Although there are other electronic machines like game consoles designed for playing games.

Video games are created in different ways. Some games are developed using game engines like Unity or Unreal. Some games are created using a plain code like Python or C++.

boy playing donkey kong arcade box

Choosing a way of developing games completely depends on your knowledge of programming languages. If you know how to code in C#, then Unity may be the best option for you. If you know C++ then Unreal engine is the one that could help you.

Understanding your knowledge about programming is your starting point to becoming a game developer. Of course, everyone’s different. You may find it easy to understand game development or you may find it not.

My tip for you is to find your comfort zone as it will lead you to your success. Otherwise, you will end up just giving up.

 

Introduction to Game Development

In every game development, you will find it very common to see a game loop and no we’re not talking about the game over and replay. We’re talking about the frames that loop back and forth inside your game.

This loop is very important due to its ability to check what is going on inside the game frame. Whether it is a keypress event or a mouse event, the game loop will always detect it.

Another thing to remember before starting game development is that…
Mathematics is very important. You will always be doing computations and stuff just to be able to go from one point to another.

Anyway…

For this course, we’ll be doing a very simple game. A single game to be precise. We’ll be developing a classic ping-pong game using vanilla JavaScript and HTML5.

For this, you will only need a text editor like Notepad++ or Sublime.

How to develop a pong game with JavaScript & HTML5

To start developing a single-player pong game using vanilla javascript and HTML5, open your text editor and copy the following code.

Keep in mind that it is best to always create a new folder for every time you create a new project. That way your files will be organized and easier to be accessed.

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Single Player Pong Game</title> <style> body { padding: 0; margin: 0; } canvas { background-color: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="game_canvas" width="640" height="480"></canvas> <script> var canvas = document.getElementById("game_canvas"); var context = canvas.getContext("2d"); function drawCanvas() { requestAnimationFrame(drawCanvas); } requestAnimationFrame(drawCanvas); </script> </body> </html>

With the code above, you will see that a canvas is created.

Creating a canvas using javascript

But there’s nothing in the canvas yet!

Drawing the ball

Well, to be able to add objects inside the canvas, you will need to use the context variable to draw a path or an object.

To do that, add the following code inside your script tag.

var x = canvas.width / 2; var y = canvas.height - 30; var radius = 15; function drawPlayer() { context.beginPath(); context.arc( x, y, radius, 0, Math.PI * 2 ); context.fillStyle = "red"; context.fill(); context.closePath(); }

Next, inside the drawCanvas() function, call the drawPlayer() function.

function drawCanvas() { drawPlayer(); requestAnimationFrame(drawCanvas); }

Refresh the page and you should see the object inside the canvas.

creating a ball using context 2d in html5 canvas using javascript

Awesome! Now let’s make the ball move around the canvas.

Making the ball move around

To do that, we will need to declare a set variable so just below the var radius = 15; add the following code.

var distanceX = 2; var distanceY = -2;

Next, inside the drawCanvas() function and just below the call of drawPlayer() function, add the following code.

x += distanceX; y += distanceY;

Save your code and you should have the following output.

Now there’s the issue, why is the canvas drawing a line instead of moving the circle? Well, technically the ball is moving but the problem is that the ball gets redrawn inside the canvas and over the previous balls.

To fix this, we’ll need to clear the canvas every time a new frame arrives.

So, once again, inside the drawCanvas() function and just above the drawPlayer() function, add the following line of code.

context.clearRect( 0, 0, canvas.width, canvas.height );

That should give you the following output.

 

Fixing the issue of the ball going through the canvas

The next thing that we’re going to do is to make sure that the ball won’t go through the canvas.

To do this, we’re gonna need to learn about collisions. We’ll need to check if the ball’s position is near the edge of the canvas. If it is, we’ll bounce it off the edge and so on and so forth.

Inside the drawCanvas() function and just above the x+= distanceX;, copy the following code.

if( x + distanceX > canvas.width - radius || x + distanceX < radius ) { distanceX = -distanceX; } if( y + distanceY < radius ) { distanceY = -distanceY; }

Save your code and you should be able to see that the ball bounces off as soon as it touches the edge of the canvas.

Next, let’s create a paddle for the player to control.

Creating the player paddle

To do that, we’re going to do the same process that we did for the ball. We’re going to create a new function and we’ll call it drawPaddle().

var paddleHeight = 12; var paddleWidth = 60; var paddleX = ( canvas.width - paddleWidth ) / 2; function drawPaddle() { context.beginPath(); context.rect( paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight ); context.fillStyle = "brown"; context.fill(); context.closePath(); }

And then, make sure that you call this new function inside the drawCanvas() function.

Just below the call of drawPlayer() function.

drawPaddle();

Save your code and you should have the following output.

creating paddle object for pong game using javascript and html5 canvas

The next thing that we’re going to do is to make this paddle movable horizontally with key presses.

 

Making the paddle move on keypress event

As soon as the player holds the left key, the paddle should slowly or quickly move to left and as soon as the player holds the right key, the paddle should move to the right.

To do that, we’ll need to declare a couple of key handlers.

So go back to your script and copy the following lines of code.

var paddleDistanceX = 8; var isRightKeyPressed = false; var isLeftKeyPressed = false; function keyDownHandler(event) { if( event.keyCode == 37 ) { isLeftKeyPressed = true; } if( event.keyCode == 39 ) { isRightKeyPressed = true; } } function keyUpHandler(event) { if( event.keyCode == 37 ) { isLeftKeyPressed = false; } if( event.keyCode == 39 ) { isRightKeyPressed = false; } } document.addEventListener('keydown', keyDownHandler, false); document.addEventListener('keyup', keyUpHandler, false);

In the code above, we only added an event listener to check whether the player is pressing the keycode 37 or 39.

If the keycode that is being pressed down is 37, then we make the value of the isLeftKeyPressed variable to true. The same goes to the other variable.

Right, so the next thing we need to do is to use these events to move our paddle horizontally whenever the player presses an arrow key.

To do that, copy the following code inside the drawCanvas() function and just above the x += distanceX;.

if( isLeftKeyPressed ) { paddleX -= paddleDistanceX; } else if( isRightKeyPressed ) { paddleX += paddleDistanceX; }

With your code being saved, you should be able to move your paddle like the output below.

With that, you should also be able to see that there’s an issue with the paddle and the ball.

The paddle can currently go through the canvas, and the ball can go through the paddle.

So to fix those issues, we’ll update the if statements that we just added before and we’ll add another if statement to check if the ball hits the paddle.

if( isLeftKeyPressed && paddleX > 0 ) { paddleX -= paddleDistanceX; } else if( isRightKeyPressed && ( paddleX + paddleWidth ) < canvas.width ) { paddleX += paddleDistanceX; } if ( y + distanceY < radius || ( y + distanceY > canvas.height - paddleHeight - radius && x + distanceX > paddleX && x + distanceX < paddleX + paddleWidth )) { distanceY = -distanceY; }

With your code being saved, you should have the following output.

Cool! Now everything seems to be working.

Now let’s add something to our code to check if it falls through the canvas. If it did, then we’ll restart the game. Let’s just make it simple.

Add the following code inside the drawCanvas(), just underneath the if statements that we just added earlier.

if( y + distanceY > canvas.height ) { location.reload(); }

Save your script and you should see the game restarts as soon as the ball touches the bottom corner of the canvas.

Building the brick field

After all the lines of codes we just made above, we have finally developed the most part of the game. We already have a game over function, keypress event handlers, and the ball.

The next thing that we’re going to do is to actually build the bricks for our player to destroy using the ball.

To do this, we’ll be creating another set of variables and a looping statement so we won’t manually put the bricks on the canvas one by one.

We’ll also create a new function for drawing the bricks, the same as how we draw the ball and the paddle. You may already see the pattern we do here.

Alright, so just below the variables in our code, copy the following.

var brickRowCount = 3; var brickColumnCount = 9; var brickWidth = 55; var brickHeight = 16; var brickPadding = 10; var brickOffsetTop = 25; var brickOffsetLeft = 25; var bricks = []; for( var c = 0; c < brickColumnCount; c++ ) { bricks[c] = []; for( var r = 0; r < brickRowCount; r++ ) { bricks[c][r] = { x: 0, y: 0 }; } } function drawBricks() { for( var c = 0; c < brickColumnCount; c++ ) { for( var r = 0; r < brickRowCount; r++ ) { var brickX = ( c * ( brickWidth + brickPadding ) ) + brickOffsetLeft; var brickY = ( r * ( brickHeight + brickPadding) ) + brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; context.beginPath(); context.rect(brickX, brickY, brickWidth, brickHeight); context.fillStyle = "gray"; context.fill(); context.closePath(); } } }

Next, inside the drawCanvas() function and just below the call of drawPaddle() function, copy the following code.

drawBricks();

Save your code, and you should see the same following output.

creating brick array for pong game using vanilla javascript and html5 canvas

Great! Now let’s work on how we can destroy these bricks with collisions.

Breaking the bricks!

We finally have the bricks being displayed on the canvas, but the ball is still not interacting with it as it goes through them.

What we need to do is to apply the same method that we did to our paddle but the difference is we need to destroy the bricks if the ball hits them.

To start, let’s create a new function where we calculate the collision that is happening within our game. We’ll be using the same looping statement that we did before as we are using a two-dimensional array for our brick objects.

function collisionDetection() { for( var c = 0; c < brickColumnCount; c++ ) { for( var r = 0; r < brickRowCount; r++ ) { var b = bricks[c][r]; if( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) { distanceY = -distanceY; } } } }

Next, we’ll have to add a new property to each of our brick object. This property will tell if the current brick is destroyed or not.

We’ll call this property status.

If the status property is set to 0, then the brick should be destroyed.

If the status is set to 1, then the brick should still be on the canvas.

Find the following line of code:

bricks[c][r] = { x: 0, y: 0 };

And change it to:

bricks[c][r] = { x: 0, y: 0, status: 1 };

Next, we need to check the status of each brick. So for the drawBricks() function, update the following code from.

function drawBricks() { for( var c = 0; c < brickColumnCount; c++ ) { for( var r = 0; r < brickRowCount; r++ ) { var brickX = ( c * ( brickWidth + brickPadding ) ) + brickOffsetLeft; var brickY = ( r * ( brickHeight + brickPadding) ) + brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; context.beginPath(); context.rect(brickX, brickY, brickWidth, brickHeight); context.fillStyle = "gray"; context.fill(); context.closePath(); } } }

to…

function drawBricks() { for( var c = 0; c < brickColumnCount; c++ ) { for( var r = 0; r < brickRowCount; r++ ) { if(bricks[c][r].status == 1) { var brickX = ( c * ( brickWidth + brickPadding ) ) + brickOffsetLeft; var brickY = ( r * ( brickHeight + brickPadding) ) + brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; context.beginPath(); context.rect(brickX, brickY, brickWidth, brickHeight); context.fillStyle = "gray"; context.fill(); context.closePath(); } } } }

Now, the next thing we need to do is to add the brick status property in the collisionDetection() function.

If the brick is not destroyed, we will check whether the collision is happening or not.

If there’s a collision, we’ll set the status of the brick to 0 so it won’t be drawn inside the canvas.

To do that, we’ll have to update our collisionDetection() function to the following.

function collisionDetection() { for( var c = 0; c < brickColumnCount; c++ ) { for( var r = 0; r < brickRowCount; r++ ) { var b = bricks[c][r]; if(b.status == 1) { if( x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight ) { distanceY = -distanceY; b.status = 0; } } } } }

The last thing we need to do is to activate our collision detection function.

To do that, add the following line of code to the drawCanvas() function, just below the drawPaddle() function.

collisionDetection();

Save your script, and you should have the following output.

 

Next steps

Congratulations! Now you have successfully developed your simple yet fun single pong game. You can finally move the paddle and make the ball bounce around the canvas and destroy the bricks.

If you want, you can adjust the variables and see what changes it does to the game.

Yes, the game is not totally finished as you still need a game scoring system, a sound, and a user interface.

The main purpose of this course is to introduce you to the idea of how to develop a game using vanilla javascript and HTML5.

If you have suggestions or questions, don’t hesitate to comment down below and we’ll do our best to help out.

React to this topic
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments