Public
Edited
Jan 1, 2024
1 fork
Insert cell
Insert cell
Insert cell
{
replay;

const width = 600,
height = 200,
applyGravity = force(cm.vec(0, 0.2)),
applyFriction = force(cm.vec(0.02, 0)),
movers = cm.range(25).map(() =>
object({
location: cm.vec(),
velocity: cm.vec(),
acceleration: cm.vec(),
mass: cm.random(0.1, 5)
})
);

function update(app) {
app.append(cm.clear, { fill: cm.rgb(255) });

app
.data(movers)
.process(cm.each, applyFriction)
.process(cm.each, applyGravity)
.process(cm.each, move)
.process(cm.each, collision)
.append(cm.circle, {
x: (d) => d.location.x,
y: (d) => d.location.y,
fill: "rgba(175, 175, 175, 0.5)",
stroke: cm.rgb(0),
r: (d) => d.mass
})
.transform(cm.mapAttrs, {
r: { scale: cm.scaleSqrt, range: [2, 20] }
});
}

function dispose(app) {
invalidation.then(() => app.dispose());
}

function frame(app) {
app.node().style.border = "solid #000 1px";
}

return cm
.app({ width, height })
.on("update", update)
.call(dispose)
.call(frame)
.start()
.node();
}
Insert cell
function object(options) {
return {
location: cm.vec(),
velocity: cm.vec(),
acceleration: cm.vec(),
mass: 1,
aVelocity: 0,
aAcceleration: 0,
rotation: 0,
...options
};
}
Insert cell
function force(d) {
const callback = typeof d === "function" ? d : () => d;
return (d, ...params) => {
const f = callback(d, ...params);
if (f === null || f === undefined) return;
const a = cm.vecDiv(f, d.mass);
d.acceleration.add(a);
};
}
Insert cell
function move(d) {
d.velocity.add(d.acceleration);
d.location.add(d.velocity);
d.acceleration.mult(0);
}
Insert cell
function collision(d, i, _, flow) {
const app = flow.app();
if (!d.location.inX(app.prop("width"))) {
d.location.clampX(app.prop("width"));
d.velocity.negX();
}
if (d.location.y > app.prop("height")) {
d.velocity.negY();
d.location.y = app.prop("height");
}
}
Insert cell
cm = require("@charming-art/charming@0.0.6")
Insert cell
import { quote } from "@pearmini/charming-shared"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more