Building a 2D Game in JavaScript with Physics: A Tutorial

Posted by





JavaScript 2D Game Tutorial (with physics)

JavaScript 2D Game Tutorial (with physics)

Creating games in JavaScript can be a rewarding experience. In this tutorial, we will learn how to create a 2D game in JavaScript with physics using the HTML5 canvas and the matter.js physics engine.

Setting up the environment

Before we start coding our game, we need to set up our environment. We will need a text editor to write our code and a web browser to run the game. You can use any text editor of your choice, such as Sublime Text, Visual Studio Code, or Atom. For the web browser, we recommend using Google Chrome for the best compatibility with HTML5 and JavaScript.

Creating the HTML file

Let’s start by creating an HTML file for our game. We will use the HTML5 canvas to render our game graphics. Here’s the basic structure of our HTML file:

    
      <!DOCTYPE html>
      <html>
      <head>
        <title>JavaScript 2D Game Tutorial (with physics)</title>
      </head>
      <body>
        <canvas id="gameCanvas" width="800" height="600"></canvas>
        <script src="game.js"></script>
      </body>
      </html>
    
  

Writing the game.js file

Now let’s create the game.js file, where we will write the JavaScript code for our game. We will use the matter.js physics engine to handle the physics of our game objects. Here’s a simple example of how to create a game object with physics using matter.js:

    
      var Engine = Matter.Engine,
          Render = Matter.Render,
          World = Matter.World,
          Bodies = Matter.Bodies;

      // create an engine
      var engine = Engine.create();

      // create a renderer
      var render = Render.create({
        element: document.getElementById('gameCanvas'),
        engine: engine
      });

      // create two boxes and a ground
      var boxA = Bodies.rectangle(400, 200, 80, 80);
      var boxB = Bodies.rectangle(450, 50, 80, 80);
      var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

      // add all of the bodies to the world
      World.add(engine.world, [boxA, boxB, ground]);

      // run the engine
      Engine.run(engine);

      // run the renderer
      Render.run(render);
    
  

With this code, we create a simple game with two boxes and a ground, all affected by physics. You can further extend this code to create your own game with different game objects and interactions.

Conclusion

Creating a 2D game in JavaScript with physics can be a fun and challenging project. With the help of the HTML5 canvas and the matter.js physics engine, you can create engaging games that are both visually appealing and interactive. We hope this tutorial has provided you with a good starting point for creating your own JavaScript games with physics.

0 0 votes
Article Rating
30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Franks laboratory
11 months ago

🍄 EXTENDED class with BONUS lessons and more free sprite sheets, full source code from 6 different stages, HQ image source files and more:

🍄 Udemy: https://www.udemy.com/course/build-animated-physics-game-with-javascript/?referralCode=B4482AF631243104650B

🍄 Skillshare (free 1 month trial):

https://www.skillshare.com/en/r/profile/Frank-Dvorak/507488567?gr_tch_ref=on&gr_trp=on

64jcl
11 months ago

A very nice long video showing that for many simple games you do not need a game engine. Html, CSS and Javascript is more than enough really. It is more enjoyable creating these components as you make your game over puzzling over some object hierarchy and dropdowns to connect stuff in game frameworks imo. You can also package this game as a standalone executable by using for example NWJS or some other tool. Btw, I'd likely make a common class abstraction for any object in the game as they had so many common things with only some parameterized variations in how they displayed from their sprite sheet + collision circle. Could reduce code size by quite a bit and would develop the first somewhat generic object type that could be then reused for any other type of game you wanted to make. It is also possible to make these games without canvas even, but by just moving e.g. DIV elements around with images inside them (can use a sprite sheet just as well for this by setting background image and offset for example). CSS has a lot of powerful effect stuff even to simplify anything from drop shadows to display effects, and triggering these is as simple as giving the element in question a class.

André Vega
11 months ago

Regarding my delta time I use a m1 macbook pro and a huawei monitor. My macbook has a 8.33, so 120 fps and my monitor is 13.33 so about 75 fps.

Bachhu
11 months ago

this is so cool

Hannes Rähmer
11 months ago

So good on so many levels. I use JavaScript only a little for smaller projects but never really got too familiar with ES6. So it was really great to see this. And all the game mechanIcs… I mean what shall I say what hasn't been already said in the comment section. Super mega thanks for the efforts put into this, Frank! Must have taken quite a long time! Much appreciated.
Did add "R" reset only on gameOver = true,
Didn't notice any difference when playing with FPS on my MacBook. May be I did something wrong here. Anyways, loved the mechanics. Really helps as a dive into game development.

Zoltán Halmay
11 months ago

I did it, it was so amazing!!!

Okani Yoshiii
11 months ago

Hi ! I just wanted to say that your video is just awesome ! It's well explained, there are a lot of efforts put on the montage to detail how things works and how you are calculating things and your code seems super clean !

I'm pretty new to Javascript and I use it mainly to add interactivity to website, not to create games and this just blew my mind ! I was just thinking : "wait, I can create video games like this with Javascript too ?! How awesome is that ?!"

I haven't finished the video yet and I'm a Javacript beginner but maybe you should create a "Entites" Class containing the "Collision" method for example and the use "Extends" to create variations of this "Entities" object. A lot of Game Objects have same or similar methods so I guess you can do something like this to gain some time, write less code and to increase general readablity.

Hope that helps ! 😀

OmegaMonkey
11 months ago

Thank you for doing this, I've been really hungry to learn, and am thankful that you made this so I pass time and learn something.

DevBoy
11 months ago

I did it

DevBoy
11 months ago

I'm a front end developer; and I ALwas struggled with javascript which seems hard for me to use cause I have a poor understanding of it's advanced concepts. but since I discovered this channel I fell that I'm being more confortable with it; and I fell that I enjoy while learning. Thank you for The big effort you put in these videos.

Coke Mayi
11 months ago

From the handkerchief you're wearing, it looks like you're a pedophile

Alejandro Diez
11 months ago

I did it!! first time I ever get involved in videogames development, thank you so much Frank you are great!!

OnUber
11 months ago

I just have the firefly blink between 2 colors to give the impression of flashing

Artem
11 months ago

This is The Brilliant Content! THanks a lot!

James
11 months ago

Promo_SM 💖

Mostafa Ragab
11 months ago

I'm having trouble accessing the asset links. are they working?

Enrique Gutierrez
11 months ago

I love your tutorials, but one thing threw me off for days. I wanted to delay the start of the game to display a welcome message. Because the lastTime was initiated with zero, I got a big deltaTime in my first loop (timeStamp was way higher because it is automatically initialized at the window load). There for a better way is to initialize lastTime with null and in the game loop set the lastTime to timeStamp if it is null. That way the lastTime is accurate.

Tom Vervecken
11 months ago

Hi Frank, thank you for your amazing tutorials. Just a suggestion, when you add the images in the HTML page, would be a lot easier to wrap them in a div or whatever.. and then in CSS you have to set display to none only once for this container div (and not for each image), no matter how many artwork you add.

Jason Boyd
11 months ago

Hey man. I was a game developer for many years. I am liking watching a lot of your tutorial vids. Mostly stuff I know but picking up a few tips here and there and its all inspirational. Cool stuff!

miguel pereyra
11 months ago

miguel