Create Game using Matter.JS with React

Anil Verma
2 min readFeb 13, 2021

--

How to create animations(games) using matter.js with React.

Matter.JS is a 2D rigid body physics engine written in JavaScript. helps in easily simulating 2D physics in the browser. It is supported in almost all browsers. We can create 2D games very easily using this lib.

Following Properties are must create a Matter js game

Engine = Matter.Engine, //it is a physics engine that needs to run create the layout by combining all bodies

Render = Matter.Render, //it is used to render your canvas layout inside your div/element

World = Matter.World, //it is the whole area where your rendered game/canvas will show

Bodies = Matter.Bodies // it is used to create a different kind of elements inside the canvas

Steps to create a simple demo with React

Step 1. In Your React App Install package

npm install matter-js

Step 2. Create a component and import Matter.JS

import Matter from 'matter-js'

Steps 3. Create an Element/div where you want to show the game/layout like below

render() {return (<div ref={this.simDivObj} ></div>)}

Step 4. Create ref of this div like

simDivObj = React.createRef();

Step 5. Inside componentDidMount life cycle create

componentDidMount() {var Engine = Matter.Engine,Render = Matter.Render,World = Matter.World,Bodies = Matter.Bodiesvar engine = Engine.create({});//create renderer on screenvar render = Render.create({element: this.simDivObj.current,engine: engine,options: {width: 800,height: 400,wireframes: false,}});var boxA = Bodies.rectangle(200, 60, 80, 80);var ballA = Bodies.circle(180, 100, 40, 10);var ballB = Bodies.circle(230, 40, 40, 10);var ballC = Bodies.rectangle(260, 60, 80, 70, {//isStatic: true,restitution: 1,render: { fillStyle: 'blue' }})var ground = Bodies.rectangle(400, 380, 800, 70, { isStatic: true });World.add(engine.world, [ground, boxA, ballA, ballB, ballC]);Engine.run(engine);Render.run(render);}

Now Run NPM START.

Ref- matter.js website

Code is available https://codepen.io/anilvermaspeaks/pen/LYbxyKY

Happy Coding….

--

--

Anil Verma
Anil Verma

Written by Anil Verma

Hi there 👋, I am Anil Verma, a full stack web developer, and JavaScript enthusiast. 👥 Ask me anything about web development. web- https://anilvermaspeaks.in/