Search code examples
javascriptphaser-frameworkphysics-enginematter.js

Outcome always different in matter.js physics engine


I created a simple animation in matter.js physics engine, with a few object colliding and falling on the ground.

I noticed that the outcome is always a little different. You can see here: https://jsfiddle.net/95urgeqf/1/

        var Engine = Matter.Engine,
            Render = Matter.Render,
            World = Matter.World,
            Bodies = Matter.Bodies,
            Body = Matter.Body;

        // create an engine
        var engine = Engine.create();

        // create a renderer
        var render = Render.create({
            element: document.body,
            engine: engine
        });

        // create two boxes and a ground
        var boxA = Bodies.rectangle(400, 200, 80, 80);
        var boxB = Bodies.rectangle(450, 50, 80, 80);
        var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });
        var circle1 = Matter.Bodies.circle(400, 200, 20, { isStatic: true }, 300);
        var circle2 = Matter.Bodies.circle(600, 300, 20, { isStatic: true }, 300);
        var circle3 = Matter.Bodies.circle(200, 400, 20, { isStatic: true }, 300);

        Body.setVelocity(boxA, { x: 0, y: -10});

        // add all of the bodies to the world
        World.add(engine.world, [boxA, boxB, ground, circle1, circle2, circle3]);

        // run the engine
        Engine.run(engine);

        // run the renderer
        Render.run(render);

Most noticeable is the square on the left when it touches the ground, it always falls a little different.

My aim is to create an animation that always behaves the same, so the left square should fall on the ground the same, identical, way each time, as long as it has the same params.


Solution

  • You got to use the same seed.

    Matter.Common._seed = 12345678;
    

    Anyway your animation can be different on different platforms/browsers due to difference in floating point operations.

    If you want exactly the same behavior you need to use fixed point math.

    UPD:

    Also you need to use seeded random number generator(for example) across all application.