I'm trying to integrate a game, built with matter-js, into my existing SvelteKit webapp but am getting stumped as to why gravity is not affecting the circle body I'm adding. The following is the typescript code within my svelte file:
onMount(async () => {
const Matter = await import('matter-js');
const canvas = document.getElementById("canvas")!
const engine = Matter.Engine.create();
const ball = Matter.Bodies.circle(100, 0, 10);
Matter.Composite.add(engine.world, ball);
Matter.Engine.update(engine);
const render = Matter.Render.create({
element: canvas,
engine: engine,
})
Matter.Render.run(render);
Matter.Runner.run(engine);
})
The ball is stuck in the initial position set within the circle() method. I'm using vite for the local dev server.
The snippet in the question isn't complete and reproducible--it's basically standard boilerplate, so I suggest providing full context (complete, runnable code). But in the meantime, I'll take a stab at a solution.
When Matter.js released 0.20, the behavior of Runner.run()
changed. In 0.19, Runner.run()
will automatically create a runner for you if one wasn't provided, but in 0.20, you need to create it yourself. No error occurs if you don't--MJS will just silently not run.
If you're using 0.19, you can use this:
const canvas = document.querySelector("div");
const engine = Matter.Engine.create();
const ball = Matter.Bodies.circle(100, 0, 50);
Matter.Composite.add(engine.world, ball);
const render = Matter.Render.create({element: canvas, engine});
Matter.Render.run(render);
Matter.Runner.run(engine);
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<div></div>
If you're using 0.20, you can use this, (which is also compatible with 0.19):
const canvas = document.querySelector("div");
const engine = Matter.Engine.create();
const ball = Matter.Bodies.circle(100, 0, 50);
Matter.Composite.add(engine.world, ball);
const render = Matter.Render.create({element: canvas, engine});
Matter.Render.run(render);
Matter.Runner.run(Matter.Runner.create(), engine);
// ^^^^^^^^^^^^^^^^^^^^^^^^
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.20.0/matter.min.js"></script>
<div></div>
To possibly reproduce your error, run the 0.19 code with 0.20 and observe that the ball is not affected by gravity (actually, the entire engine does not run).
Note also that document.getElementById("canvas")!
should be a container for the canvas MJS will create and inject a canvas into. If you're using your own canvas, you wouldn't need a Matter.Render
. You can also use the canvas:
property rather than element:
if you want to specify a canvas.