Add the gravity.js file into your project and include it in your HTML head tags:
<script src="https://cdn.jsdelivr.net/npm/@idevgames/gravity-js/src/gravity.js"></script>
Or use npm:
npm i @idevgames/gravity-js
Add the data attribute "data-gravity" or class "enable-gravity" to your HTML element to make it a physics body:
<div data-gravity data-gravity-type="dynamic"></div>
The element will automatically become a physics body and respond to gravity and collisions!
Three body types are available via data-gravity-type:
Set collision shape with data-gravity-shape:
Customize physics behavior with these data attributes:
Set initial motion or continuous forces:
Gravity.js exposes physics state as CSS variables:
Use these in your CSS for dynamic effects based on physics state!
Collisions are detected automatically and trigger:
Create trigger zones with data-gravity-sensor="true":
<div data-gravity data-gravity-type="static" data-gravity-sensor="true"></div>
Sensors detect collisions but don't create physical responses. Perfect for trigger zones, checkpoints, and event areas!
Filter collisions with data-gravity-group:
<div data-gravity data-gravity-group="player"></div>
<div data-gravity data-gravity-group="enemy"></div>
Bodies only collide with others in the same group or the default group.
Configure global physics on the body element:
Optional JavaScript methods for advanced control:
gravity.applyForce(elementId, x, y)
gravity.applyImpulse(elementId, x, y)
gravity.setVelocity(elementId, x, y)
gravity.getBody(elementId)
gravity.pauseSimulation()
gravity.resumeSimulation()
Gravity.js works seamlessly with State.js for game state management:
<div id="player" data-gravity data-state data-state-watch="collision-with"></div>
<div id="coin" data-gravity data-gravity-sensor="true"></div>
Collision events update data attributes that State.js can watch and react to. Use collision sensors to trigger state changes!
Combine with Keys.js for player input:
document.addEventListener('keydown', (e) => {
if (keys.isKeyDown('space')) {
gravity.applyImpulse('player', 0, -300);
}
if (keys.isKeyDown('right')) {
gravity.applyForce('player', 50, 0);
}
});
Create fully interactive games with physics, input, and state management!
Gravity.js + State.js + Keys.js = Complete Browser Game Engine
Check out the companion libraries: