To use the engine, initialize a System with configuration options, create entities (such as Circle), and run a loop that calls system.update(dt) to advance the physics simulation.
Core Components
System: The main engine instance that manages entities and physics calculations.Circle: A type of entity representing a circular body.Vector: A utility class for handling 2D coordinates and physics vectors.
Simulation Loop and Error Correction
When running the simulation, calculate a dt (delta time) value to act as an error correction mechanism. This scales time-variant operations if the interval does not run exactly at the specified MSPT (milliseconds per tick).
/** Create a system with 100 circles. */
const { System, Circle, Vector } = require("kinetics.ts");
const system = new System({
tickRate: 60,
friction: 0.1,
collisionInfo: {
cellSize: 6,
},
bounds: new Vector(1920, 1080)
});
for (let i = 0; i < 100; i++) {
const radius = 10;
const entity = new Circle(
{
form: {
vertices: [new Vector(0, 0)],
},
radius,
mass: 10,
speed: 1,
rotate: false,
elasticity: 1,
angularSpeed: 1,
},
system
);
system.addEntity(entity);
}
/** The number of ticks the engine will run per second. */
const FPS = 60;
/** The ideal time it will take for one system update. */
const MSPT = 1000 / FPS;
/** The timestamp of the last engine update. */
let lastTimestamp = 0;
setInterval(() => {
let currentTime = performance.now();
let deltaTime = currentTime - lastTimestamp; // time in between two ticks
lastTimestamp = currentTime;
// `dt` is a sort of error correction mechanism.
// In the event the interval doesn't run at the specified
// MSPT, `dt` corrects all time variant operations by scaling
// them by its value.
const dt = Math.min((deltaTime / MSPT), 3);
system.update(dt);
}, MSPT);