Learn Matter.js with examples - Basics of using a physics engine in JavaScript - Main image

Intermediate

Learn Matter.js with examples - Basics of using a physics engine in JavaScript

Learning Matter.js with examples is the most fun way of learning what a physics engine is. A physics engine is used for simulating physics effects in apps.

Nera Husarević - CodeBrainer
Nera Husarević
14 min read

Learning Matter.js with examples is the most fun way of learning what a physics engine is. A physics engine is used for simulating physics effects in apps. It is great for beginners, since it does not require advanced programming, while it still offers a variety of visually pleasing possibilities. 

Matter,js is a 2D physics engine written in JavaScript. It is suitable for mobile devices, since it has the ability to detect touch, while it supports all major browsers. If you have been following our game development articles you should know matter.js is also useful for building games, making websites/webapps less static and more interactive.

Here you can learn the basics of using matter.js physics engine. We will show you matter.js with examples of making objects have simulations of physical forces. Feel free to try them and show us your work.

In this article we will show you how to:

  • Set up matter.js
  • Connect your HTML, CSS and JavaScript files
  • Create fun examples of matter.js

Examples of matter.js in this article:

  • Create falling objects using gravity
  • Make a flying balloon
  • Create balloon that is tied to the rope
  • Develop your own slingshot game

Ballon - matter.js example

Adding matter.js to your project (Installation)

Installation using CDN:

Usually, matter.js is installed through CDN website or using package manager.

<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.17.1/matter.min.js"></script>

In our examples for matter.js we are using this method as it is easier to try out, since everything is done for us just by using a CDN link.

 

Installation using package manager (npm):

Install using package manager by using the command: 

npm install matter-js

Install using the CDN link, all you have to do is include it in your project. This is done in the HTML 

<script src="path/to/matter.min.js"></script>

Remember to put script tag inside the HTML tag.

 

The HTML for our examples

Starting with the simple HTML file, where we will connect it to the JavaScript, integrate some CSS and call our init() function. Here we will also define the <canvas> element, which is used for drawing 2D graphics. You can read more about it in our upcoming article, which introduces the basics of its use.

HTML
HTML for matter.js examples - HTML - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Just to let you know in between the empty <div> tags (at the end of HTML document) we will add some elements later on.


The base code for our matter.js examples

To render shapes with matter.js to the so called “world”, we first have to create it with a few simple initializations. These are few more module aliases we have set up so it is easier to reference the matter library:

JavaScript
The code base for our matter.js examples - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!


The first variable, Matter.Engine module, enables all the methods for using the engines, which updates the simulation of the “world”. If you have ever encountered any game development, you are probably already familiar with the term renderer. Matter.Render is a basic HTML canvas-based renderer. Then comes the Matter.Runner module, which enables a game loop. Matter.Bodies is a module that contains factory methods for creating body models. Bodies are somewhat objects, such as shapes (rectangles, circles, etc.)

Moving on to the:

JavaScript
The code base for our matter.js examples - composits - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The next module, Matter.Composite, represents a container for more compound objects, which can have multiple parts. We used Matter.Composites as well, which enables factory methods for drawing more commonly used layouts. Next up is Matter.Constraint for creating and manipulating constraints. The previously mentioned Matter.Composite is an assembly of Matter.Body, Matter.Constraint and Matter.Composite. That is why a composite can contain even a whole world.

For managing the mouse inputs, we used the Matter.Mouse, and Matter.MouseConstraint for creating its constraints. Lastly we have the Matter.Events, which includes methods for firing and listening to events on other objects.

JavaScript
Main variables - code base - material.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The last three lines are variables dedicated to the objects for the work with matter.js.

The next part of our JavaScript code is the init() function.

JavaScript
Init function - code base - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

At the beginning of the function, we used a previously declared variable engine to create the engine itself. Then we also created the renderer in a similar way, except we added some attributes to it. After that we run both the engine and the renderer.

Purpose of an init() function is to return the initial result of the aggregate. It can take in up to two arguments with the first one being the same data type as the aggregated column.  

The upcoming part of our code is the clearWorld() function. Its purpose is clearing up the canvas when switching between the examples. 

JavaScript
Clear world - code base - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

 

A Few fun examples you could try on your own with matter.js

Falling boxes - Create falling objects using gravity

You can best showcase matter.js with examples. Our first and most basic example will be creating simple rectangles (boxes) falling from the top of the screen. We will also create a ground for them to fall on. Purpose of this example is to show the imitation of the gravitational force. 

Falling boxes - matter.js example

The function for the creating boxes looks like this:

JavaScript
Falling boxes example - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The first part of the function is the call of the clearWorld() function which we created right after init(). Its purpose is to clear the specific example.

Then we create the boxes (boxA, boxB) by defining them as rectangles, which will become objects. We specify the coordinates they will spawn at and their size. If you look at these arguments, you may notice that one box will spawn a bit lower than the other. While rendering objects we can also determine their color and style, one of our boxes will be red with a blue border. 

After rendering our boxes, we also define the ground, which is also presented by a wider rectangle. We made it static, since it is an obstacle that does not change. Concerning this function, the only thing left to do is add these bodies to the world using the Composite.add and update the engine. 

 

Make a flying Balloon using matter.js

Next example in matter.js is not a common one. We decided to get creative and show something a bit more fun. Here is how you write a function which creates a balloon. Using the physics engine, we will make the balloon float up.

Ballon - matter.js example

The code we are using to make a balloon fly is:

JavaScript
Balloon example - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

We again start by clearing the specified example and setting the world density to 1. Mass and inertia are automatically updated to reflect the change. Then we create the balloon by defining it as a circle. We also determined its position, size and mass. Just like with the boxes, we styled it by rendering color, border and line width. The ground stays static just like previously. 

To make a balloon fly we have to simulate a force. The applyForce applies the force to the body given the position, mass and size, by also using the Matter.Body module to manipulate the body (object). For learning purposes and experimentation, you could try switching the /100 with /50 or /150. Let us know what happens!

 

Balloon tied down with string

Ballon with string - matter.js example

To create a balloon, which is tied down with a string, we just add a few things to the previous function, just in this case we create only a single balloon. Right before the function you might notice an array definition. The ropes array. We use this array to apply force to the balloon. Like we applied force for the flying of the balloon in the previous example, we now tighten the string to the balloon using apply force.

We clear the balloonWithString example and again set the world density to 1.

JavaScript
Balloon with rope example - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

Up to this part most of our function stayed the same, simply creating the balloon as a circle and rendering it. From now on the changes start.

JavaScript
Balloon with rope example II - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

To create the balloon with a string, we just add a few things to the previous function. Firstly we created a rope using Constraint.create and rendered its properties. These properties include its spawning position and color of the rope (gray). Then we pushed it into the ropes array. Lastly for this part, we apply the force which tries to pull the balloon up. In contrast to the previous example, the balloon will not be pulled up due to the effect of the rope. 



Cutting the balloon rope

The following function will just remove the rope we created before. The purpose is to see how this situation looks created with the physics engine. 

Ballon with string - cut the rope - matter.js example

The code for cutting the rope is:

JavaScript
How to cut rope for the balloon example - matter.js - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

As mentioned, we just used the Composite.remove for removing the rope. This generic remove() function, removes one or more bodies from the given composite, thus the parameters engine.world and rope.

 

The Slingshot game example

As you may have noticed from our recent blog and media posts, we at CodeBrainer enjoy making games. Both simple and complicated. To apply this amazing study method to matter.js engine as well, here is an interesting example of a slingshot game. The point of the game is to shoot the blocks on the “shelf” by pulling a rock back and letting it go after aiming. Quite similar to the famous Angry Birds game.

Sling shot game - matter.js example

You can see sling shot game in action in the animation. But let's explain how the code works.

JavaScript
Sling shot game using matter.js - Create the World - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

In the beginning of the StartSlingshot() function, we clear the canvas for the specified example, just like up till now. The following definitions are variables reserved for all the bodies we will use, such as the ground, the rock and its options, the anchor and the elastic which holds the rock. For the elastic we also specified the points which hold it, its stiffness, the render color (grey) and stroking width. The ground2 variable represents the “shelf” which holds the pyramid of blocks (rectangles), which are also defined right after. The pyramid definition also includes a function for returning the blocks and this function takes in coordinates  (x and y).

JavaScript
Sling shot game using matter.js - Mouse movements - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

To be able to aim with our mouse cursor, we also have to include the mouse control. Here we used the MouseConstraint for creating the mouse constraint, specifying its stiffness and rendering it. We made these mouse actions invisible by making the visible parameter false.

JavaScript
Sling shot game using matter.js - Mouse movements - rock release - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The Events.on method calls a function on the specified object’s eventName, which is in this case ‘afterUpdate’. The upcoming function uses the if statement to determine where the rock is positioned. To put it simply, it checks if the player is aiming and enables shooting the rock to the aimed position. 

JavaScript
Sling shot using matter.js - Add elements - JavaScript - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

The final part of our StartSlingshot() function is to add all the composites to the engine world and let the mouse movement sync with the rendering.

 

Link all matter.js examples with main HTML page

After you have written down all the JavaScript functions, it is only logical to call them. Our way of doing this was by adding buttons into the <div> element of the HTML file. Each button has a text inside, which describes what it does. Inside the opening brackets of the <button> tag we included the onclick event and called the designated function for the event.

HTML
Buttons for Matter.js examples - HTML - HTML - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

 

Conclusion

Explaining matter.js with examples shows what a physics engine offers. Matter.js engine offers a sea of modules for simulating the real physical forces. It is a great tool for game development or just interesting and eye-catching website details. We hope this article and examples included introduced you to the basics of the use of this engine. Feel free to try any of them and let us know how it went, show us any interesting examples you have come up with and do not feel restrained to ask for our help with your code. We challenge you to attempt making a game in which the player attempts to carry an object without moving/affecting any obstacles. Would you like a tutorial on such a game as well?