0
0
Fork 0
mirror of https://github.com/liabru/matter-js.git synced 2024-11-21 09:06:50 -05:00
16 Getting started
liabru edited this page 2021-12-15 10:46:50 +00:00

A simple guide to getting started with Matter.js

  1. Install
  2. Usage examples
  3. Running and Rendering
  4. Documentation

Install

Download the latest build or get a release version and include the script in your web page e.g.

<script src="matter.js"></script>

You can also install using the package manager npm

npm install matter-js

Webpack

Some webpack configs including the default may impact your project's performance during development, for a solution see issue.

Usage example

The following is a minimal example using the built in renderer and runner to get you started:

// module aliases
var Engine = Matter.Engine,
    Render = Matter.Render,
    Runner = Matter.Runner,
    Bodies = Matter.Bodies,
    Composite = Matter.Composite;

// 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
Composite.add(engine.world, [boxA, boxB, ground]);

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

// create runner
var runner = Runner.create();

// run the engine
Runner.run(runner, engine);

Include the above script into a page that has Matter.js installed and then open the page in your browser. Make sure the script is at the bottom of the page (or called on the window load event, or after DOM is ready).

Hopefully you will see two rectangle bodies fall and then hit each other as they land on the ground. If you don't, check the browser console to see if there are any errors.

Check out the demo page for more examples and then refer to Demo.js to see how they work. Some of the demos are also available on codepen, where you can easily experiment with them (but they may not always be completely up to date).

Running and Rendering

The above example uses the built in renderer and runner, but these are both optional and it's easy to render in your own way and use your own game loop. See the Rendering and Running wiki pages for information.

Documentation

See the Matter.js Documentation for detailed information on the API.