Matter.js – The Basics for Developing Games

Matter.js demo

Sharing is caring!

What is Matter.js

Matter.js is a JavaScript physics engine based on the popular box2d physic engine wrote in c++. It allows the programmer to make objects that act more realistically. With the Matter.js engine, you can create games that have realistic falling objects, explosion effects, composite objects, react to certain events etc. A basic example of what can be made is available here on codepen as well as some examples provided on brm.io. Sure you could program all the physics yourself, but why do all the extra work for a slightly more streamlined game when you could save a lot of time using matter.js. The video below shows what we will be making.

[embedyt] http://www.youtube.com/watch?v=7lfhsUNWIlA[/embedyt]

For this example, we’re going to make a simple world where you control a square using the w,a,d keys and can jump with space. There will be objects to jump over and push about with the player square and we will react to events such as keys and on collisions. We will also listen to mouse events and add objects on clicks.

Setting up the canvas

In order for our world to be seen by the user, we have to create a canvas on an HTML page. With Matter.js this can be done automatically, but I like to add it myself so I have more control over the canvas properties. We will make a basic HTML page with  <html>, <body> etc and then add our canvas. We need to import our Matter.js script in our head section so we can use it. Your code should look similar to this code:

In the code above we have added our canvas to our HTML page. We set the ID of the canvas to cv so we can reference it in our JavaScript code later. We have also set some styling to our canvas and body to style the page.

Setting up the Engine

Now we have a canvas to draw our objects on we need to set up the Matter.js engine and add some objects. But before we do that, let’s get a reference to some things we will need later on. We will need a link to our canvas in JavaScript as well as a link to the canvas context. Since we don’t know the screen size of our users we will have to set the canvas size when the user loads the page and finally set up our Matter.js engine modules.

 Creating objects

Now we have our modules setup for easier access we need to create the Matter.js engine and start adding objects. To create the engine all we need to do is var engine = Engine.create(); simple no? Now we have an engine we can start adding objects. Let’s start with the player object. In order to create an object, we use the bodies module which controls the creation of bodies. Our player body is created like this var playerBody = Bodies.rectangle(window.innerWidth/2,225,20,20,{density:0.002, friction:0.5}); This create a new rectangle shape in the horizontal center of the screen, 255 pixels down from the top, 20 pixels wide, 20 pixels high with the density option set to 0.002 and friction set to 0.5. Density and friction are optional entries and can be left out to use the default values. In the most basic example of creating a body you just use Bodies.rectangle(x-position,y-position,width,height);

Adding bodies together

Now we can add single bodies but how to we stick two or more bodies together? Well, we use the same function Bodies.create() except this time we add an array of objects to the parts option. Since we will have a player that can jump and we only want the player to jump when he is on the ground we will use a normal body together with a sensor body to sense when they’re on the ground. The code to add 2 body parts together as one body looks like this:

The player body is made up of 2 parts, playerBody and playerFloorSensor. Here we use a sensor. A sensor is a body that does not physically interact with other bodies but allows us to check wether the sensor is colliding with other objects.

The below code is all the bodies we will be adding in this tutorial. Some of which are static objects which means they will not move or be affected by the weight of other bodies.

In the above code you can see that the objects were created and then added to the world using World.add(); This adds the bodies to the world so they physically exist in the world and will react to physic forces.

Rendering objects

Now we have our world with objects inside, we need to tell the engine to run. The running of the engine will mean physic forces will start to effect objects in the world and it’s as simple as Engine.run(engine); This is the default run loop provided by Matter.js which controls the game logic. In your own game, you can create your own run loop explained here on the Matter.js wiki. With the game loop out of the way, we can start on the rendering aspect. In our render function, we will want to react to key presses, mouse clicks and render our objects.

In the above code, you can see we have used several if statements to check if keys have been pressed. Inside these statements, we apply a force to our player body depending on the key. In the if statement for the click, we add a new object to the world if the mouse button is down. This will create a lot of objects and should be adjusted to only add objects if there are currently no objects already or you will end up with thousands of objects on the screen all in the same place. Once we have reacted to all the inputs from the user we grab a reference to all the bodies in the Matter.js world using Composite.AllBodies(engine.world) and then later loop through all the bodies in a for loop and create a path on our canvas, which is then stroked and filled. More information on canvases and drawing on them can be found on a previous post custom-404-error-pages.

Reacting to user input

The Matter.js world and all the bodies are now set to render and react to physical forces. We now need to add user input and this will be done using JavaScript addEvenetListener and the Matter.js Events module. We need some flags and arrays for our keys, mouse and player status.

Here we added some Constants so it’s easier to remember which keys are which. We also added a flag for the player to state whether they are on the floor or not as well as an array for the keys and a variable for the mouse position(mp)

With the variables ready we need to add a Mouse constraint which is used to capture mouse events in Matter.js. Code below:

Now we have a mouse constraint we need to add functions to fire off when the event takes place. This is done by using the Events module of Matter.js.

Here we listen for mouse events and set the mouse position and mouseIsDown flag. Yay! we now  react to mouse clicks.

Finally, we need to react to collision events. Collision events are fired when two objects hit each other. This will allow us to know when our player in on the floor as we have a sensor on the bottom of our player. Again we use the Events module from Matter.js to react to these events. The code below has 3 events for collisions; collisionStart which is fired only on the first collision frame, collisionActive which is fired each frame the objects are touching and finally collisionEnd which is fired when the objects no longer touch.

We have now finished and the page can be opened in a browser and run. A complete code example can be found here on StoreMyVids.

 

If you know of any good guides, tutorials or websites for matter.js please feel free to add them in the comments 🙂

Sharing is caring!

One Reply to “Matter.js – The Basics for Developing Games”

  1. Excellent tutorial. Patient and detailed explanations with

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.