Matter-js: Check if world is sleeping

Created on 8 Nov 2016  路  6Comments  路  Source: liabru/matter-js

First of all, simply amazing work on the library and maintainment, bravo!

Question: is there a built-in method/event to detect when the world is still/sleeping, as in there is no movement on any body? I'm aware it can be detected for bodies individually.

question

All 6 comments

Nothing built in for this, I'd suggest something like:

let bodies = Composite.allBodies(world);
let sleeping = bodies.filter((body) => body.isSleeping);
let isWorldSleeping = bodies.length === sleeping.length;

Thank you for the answer!

@liabru Another question. Isn't isSleeping === true supposed to mean that a body has stopped movement? In my tests bodies actually never end up in this state.

I'm simply trying to detect when all objects in the world have stopped moving.

Okay, it simply seems that, while being invisible to the eye, the objects actually maintain just a tiny amount of speed. What I did for now:

let isAwake = false;
const bodies = Matter.Composite.allBodies(world);

for(let i = 0; i < bodies.length; i++) {
    if(bodies[i].speed > 0.005) {
        isAwake = true;
        break;
    }
}

if(!isAwake) {
    for(let i = 0; i < bodies.length; i++) {
        Matter.Body.setVelocity(bodies[i], { x: 0, y: 0 });
    }
}

Maybe there is a more elegant solution?

Do you mean actual sleeping, which you have to enable or do you just mean 'come to rest'? If it's the latter then try something like this in the filter:

let motion = body.speed * body.speed + body.angularSpeed * body.angularSpeed;
let isResting = motion < 0.1;

I meant detecting when all objects/bodies have stopped moving. My bad on confusing the terms. Thank you again.

Was this page helpful?
0 / 5 - 0 ratings