So I made a little matter.js thing, using javascript and html, it just creates a black floor, where which a rectangle, trapezoid, square, and circle fall on it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- Include the local Matter.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.js" integrity="sha512-rsntMCBgWYEWKl4HtqWmQ3vdHgvSq8CTtJd19YL7lCtKokLPWt7UEoHVabK1uiNfUdaLit8O090no5BZjcz+bw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
// module aliases
let Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Bodies = Matter.Bodies,
Composite = Matter.Composite;
// create an engine
let engine = Engine.create();
engine.world.gravity.y = 1;
function changeGravity()
{
engine.world.gravity.y = 0;
}
// create a renderer
let render = Render.create({
element: document.body,
engine: engine,
options: {
wireframes: false,
background: ''
}
});
let RenderOption = {
isStatic: false,
render:{
fillStyle: 'black',
strokeStyle: 'red',
lineWidth: 5
}
}
// create two boxes and a ground
let boxA = Bodies.rectangle(400, 10, 100, 200, RenderOption);
let boxB = Bodies.rectangle(450, 50, 80, 80, RenderOption);
let circle2 = Bodies.circle(500, 40, 50, RenderOption);
let ground = Bodies.rectangle(400, 610, 900, 90, {
isStatic: true,
render:{
fillStyle: 'black'
}
});
let trapezoid = Bodies.trapezoid(400, 60, 100, 100, 0.9, RenderOption);
// add all of the bodies to the world
Composite.add(engine.world, [boxA, boxB, ground, circle2, trapezoid]);
// Event listener for keydown event
document.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
changeGravity();
}
})
// run the renderer
Render.run(render);
// create runner
let runner = Runner.create();
// run the engine
Runner.run(runner, engine);
console.log("Engine created:", engine);
console.log("Render started:", render);
console.log("Bodies added:", boxA, boxB, ground);
</script>
</body>
</html>
It is supposed to make the gravity 0 when the enter key is pressed.
No matter what I tried this does not work. The wierd thing if I put something like alert() or console.log everything works fine. I cant seem to find the issue.
Thanks.
2
Answers
Turns out that my keyboard was glitched.....
Sorry for the confusion!
I believe you do not need to call a function for your event listener.
For my solution, I replaced this:
With this:
That way, it should work.