javascript2dgame-physicsmatter.js

MatterJS precompute final position


I am trying to create a simple 2D game where a ball is falling to the ground, influenced by some obstacles that will change the final position of the ball.

I am using MatterJS as a 2D physics engine but it is actually unpredictable, with the same parameters my ball is always at a different final position.

Is there a way to precompute the path the ball will have (instantly), save it into a variable and load it to get the exact same path whenever I need it? Or is there a way to predict the final position accurately?


Solution

  • I found a way to precompute instantly the path of the ball by calling manually Matter.Engine.update(engine) and storing the position of my ball for each frame.

    Then i reset the position of my ball, set ball.isStatic = true; and move it manually at each frame:

    Matter.Events.on(engine, "afterUpdate", () => {
        if (positions.length > 0) {
            Matter.Body.setPosition(ball, positions.shift());
        }
    });