Welcome to a new series where I will be introducting interesting js libraries, how to implement and use them.

What is it?

Matter.js is a 2D physics engine for the web

How to Implement It

Implementing matter.js is the same as any other library, all you need to do is cite the source in your html document like so:

   <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.js" type="text/javascript"></script>

Once this step is done, you should be all set to start using matter.js library!

Things to know

Here are some things you should know to help get you started with matter.js

Matter.js is built differently compared to other Javascript libraries. The way the code is written out, and the way it is formatted is simple compared to other libraries.

Getting Started

To start a matter.js document you firstly need to establish your module aliases like so:
   var Engine = Matter.Engine,
     Render = Matter.Render,
     World = Matter.World,
     Bodies = Matter.Bodies,

Next you need to create your engine that you have just established in your module aliases

   var Engine = Engine.create();

Now we need to create our Renderer like so

   var render = Render.create({
    element: document.body,
    engine: engine
});

Now we are going to create our elements/bodies (circles, squares, rectangles, walls, floors, etc..)

  var boxA = Bodies.rectangle(450, 50, 80, 80);
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

Almost there...

Now we are going to add all of the bodies/elements to the world

  World.add(engine.world, [boxA, boxB, ground]);

To run the program all we need to do is run the Engine and the Render

  Engine.run(engine);

Render.run(render);

Now to ensure that you got everything here is the code compiled into one:

  // module aliases
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.body,
    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);

Conclusion

I hope that this little tutorial/intro has helped you to get started with using matter.js and will inspire you to continue onward with exploring this amazing library!

Enjoy!


2,394 0 18