Search code examples
javascriptmatter.js

How to draw a semicircle with matter.js?


I am playing with the matterjs library, it's awesome!

I am trying to figure out how I can draw a semicircle like these:

enter image description here

I tried with Bodies.circle, Bodies.rectangle and Bodies.polygon but with no luck.

It seems like a pretty simple shape but I don't know if it is possible to draw a semicirle with the library.

Any recommendation would be great!


Solution

  • SVGs are one approach:

    const engine = Matter.Engine.create();
    const runner = Matter.Runner.create();
    const render = Matter.Render.create({
      element: document.body,
      engine,
    });
    const bodies = [
      Matter.Bodies.rectangle(
        400, 210, 810, 60, {isStatic: true, angle: 0.0}
      ),
      ...Array(50).fill().map(() => {
        const path = document.querySelector("svg path");
        const body = Matter.Bodies.fromVertices(
          Math.random() * innerWidth, // x
          0,    // y
          Matter.Svg.pathToVertices(path), // vertexSets
          {},   // options
          true, // flag internal
        );
        const scale = Math.random() / 2 + 0.2;
        Matter.Body.scale(body, scale, scale);
        return body;
      }),
    ];
    const mouseConstraint = Matter.MouseConstraint.create(
      engine, {element: document.body}
    );
    Matter.Composite.add(engine.world, [...bodies, mouseConstraint]);
    Matter.Runner.run(runner, engine);
    Matter.Render.run(render);
    svg {display: none;}
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/pathseg.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.20.0/matter.js"></script>
    <svg>
      <!-- SVG path from https://upload.wikimedia.org/wikipedia/commons/e/e9/Semicircle.svg -->
      <path d="M 98,93 L 169,93 C 169,54 137,22 98,22 C 59,22 27,54 27,93 L 98,93 z " />
    </svg>