Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling gravity for a specific object in Matter.js

I'm working on a project using Matter.js where I want gravity enabled in general, but I want to be able to disabled and re-enable it for a single object at certain times. I do not want to set that object as static, because I want the physics engine to handle it in other ways, I just don't want gravity to affect it.

I found this question that deals with disabling gravity in general, but as I said I want gravity to work for most objects. Is there a simple way to do this?

like image 902
Teale Fristoe Avatar asked Apr 06 '16 23:04

Teale Fristoe


1 Answers

Here is a simple code snippet that you could have toggle on/off to accomplish what you're asking (where body is the object that should ignore gravity, and noGravity is a boolean that can be toggled to turn it on and off):

Events.on(engine, 'beforeUpdate', function() {
    var gravity = engine.world.gravity;

    if (noGravity) {
        Body.applyForce(body, body.position, {
            x: -gravity.x * gravity.scale * body.mass,
            y: -gravity.y * gravity.scale * body.mass
        });
    }
});
like image 113
Derek Avatar answered Sep 21 '22 21:09

Derek