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?
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
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With