JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

HTML

<script src="https://unpkg.com/[email protected]/build/matter.min.js"></script>

JavaScript

const { Engine, Render, Runner, Events, Body, Bodies, Composite, Vector } = Matter;

function field(pos) {
	let {x, y} = pos;
  x = x - 300;
  y = 200 - y;
  
  x /= 100;
  y /= 100;
  
  const angle = Math.atan2(y, x);

	return [
  	-(x-1),
    -y
  ];
}

const engine = Engine.create({
	gravity: { x: 0, y: 0 }
});

var box = Bodies.circle(100, 100, 20);

Composite.add(engine.world, [
	box,
  Bodies.rectangle(300, 10, 600, 20, { isStatic: true }),
  Bodies.rectangle(300, 390, 600, 20, { isStatic: true }),
  Bodies.rectangle(10, 200, 20, 400, { isStatic: true }),
  Bodies.rectangle(590, 200, 20, 400, { isStatic: true }),
]);

const runner = Runner.create();

Events.on(runner, "beforeTick", () => {
	const [x, y] = field(box.position);
	Body.applyForce(
  	box,
    box.position,
    Vector.create(x / 1000, -y / 1000)
  );
});

Runner.run(runner, engine);




/*
const render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 600,
    height: 400,
    // showAngleIndicator: true,
    // showPositions: true,
    showVelocity: true
  }
});

Render.run(render);
*/

const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");

canvas.width = 800;
canvas.height = 600;

document.body.appendChild(canvas);

(function render() {
    window.requestAnimationFrame(render);

    context.fillStyle = '#fff';
    context.fillRect(0, 0, canvas.width, canvas.height);
    
    context.beginPath();
    for (let x = 0; x <= 800; x += 20) {
    	for (let y = 0; y <= 600; y += 20) {
      	const vector = field({ x, y });
        
        context.moveTo(x, y);
        context.lineTo(
        	x + vector[0] * 10,
          y - vector[1] * 10
        );
      }
    }
    context.lineWidth = 1;
    context.strokeStyle = "red";
    context.stroke();


    const bodies = Composite.allBodies(engine.world);

    context.beginPath();

    for (let i = 0; i < bodies.length; i += 1) {
        const vertices = bodies[i].vertices;

       ...