I'm new to matter.js and I'm using Body.applyForce
to move my box in a platformer I'm creating. I was wondering if there was an easier function to use that allows constant movement instead of just randomly going from slow to fast.
Here's all my code:
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Bodies = Matter.Bodies,
Body = Matter.Body,
World = Matter.World,
Composite = Matter.Composite;
var engine = Engine.create();
var render = Render.create({
element: document.body,
engine: engine
});
var boxA = Bodies.rectangle(400, 200, 80, 80);
var boxB = Bodies.rectangle(600, 560, 80, 80);
var ground = Bodies.rectangle(435, 630, 810, 60, {
isStatic: true
});
var leftWall = Bodies.rectangle(0, 200, 60, 800, {
isStatic: true
});
Body.setStatic(boxB, true)
Body.setInertia(boxA, Infinity)
const cases = Object.assign(Object.create(null), {
KeyD: (Body, boxA) => {
Body.applyForce(boxA, {
x: boxA.position.x,
y: boxA.position.y
}, {
x: 0.03,
y: 0,
})
},
KeyA: (Body, boxA) => {
Body.applyForce(boxA, {
x: boxA.position.x,
y: boxA.position.y
}, {
x: -0.03,
y: 0,
})
},
})
document.addEventListener("keydown", event => {
cases[event.code]?.(Body, boxA)
})
Composite.add(engine.world, [boxA, boxB, ground, leftWall]);
Render.run(render);
var runner = Runner.create();
Runner.run(runner, engine);
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.17.1/matter.min.js"></script>