Public
Edited
Jan 1, 2024
Fork of Car Arriving
1 fork
Insert cell
Insert cell
{
const width = 600,
height = 200,
target = object(),
car = object({
location: cm.vec(width / 2, height / 2),
maxSpeed: 4,
maxForce: 0.1,
r: 6
});

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

app
.datum(target)
.process(cm.each, (d) =>
d.location.set(app.prop("mouseX"), app.prop("mouseY"))
)
.append(cm.circle, {
x: (d) => d.location.x,
y: (d) => d.location.y,
r: 24,
stroke: "black",
fill: cm.rgb(175),
strokeWidth: 2
});

app
.datum(car)
.process(cm.each, (d) => seek(d, target))
.process(cm.each, move)
.append(cm.group, {
x: (d) => d.location.x,
y: (d) => d.location.y,
rotate: (d) => d.velocity.angle()
})
.append(cm.triangle, {
x: (d) => d.r * 2,
y: 0,
x1: (d) => -d.r * 2,
y1: (d) => -d.r,
x2: (d) => -d.r * 2,
y2: (d) => d.r,
fill: cm.rgb(175),
stroke: cm.rgb(0),
strokeWidth: 2
});
}

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

return cm
.app({ width, height })
.on("update", update)
.call(border)
.call(dispose)
.start()
.node();
}
Insert cell
function seek(d, target) {
const desired = cm.vecSub(target.location, d.location).mag(d.maxSpeed);
const steer = cm.vecSub(desired, d.velocity);
steer.clamp(d.maxForce);
applyForce(d, steer);
}
Insert cell
function move(d) {
d.velocity.add(d.acceleration);
d.location.add(d.velocity);
d.acceleration.mult(0);
}
Insert cell
function applyForce(d, force) {
const a = cm.vecDiv(force, d.mass);
d.acceleration.add(a);
}
Insert cell
function object(options) {
return {
location: cm.vec(),
velocity: cm.vec(),
acceleration: cm.vec(),
mass: 1,
...options
};
}
Insert cell
function border(app) {
app.node().style.border = "solid #000 1px"
}
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