Public
Edited
Oct 20, 2022
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}

toString() {
return `[${this.x.toFixed(2)}, ${this.y.toFixed(2 )}]`;
}

div(n) {
this.x /= n;
this.y /= n;
return this;
}

mult(n) {
this.x *= n;
this.y *= n;
return this;
}

mag() {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}

setMag(n) {
this.normalize().mult(n);
return this;
}

normalize() {
this.div(this.mag());
return this;
}

// ➡️ The limit function
limit(max) {
if (this.mag() > max) this.setMag(max);
return this;
}
}
Insert cell
test = {
const max = 4;
const logs = [new Vector(100, 1), new Vector(2, 2), new Vector(5, 5)].map(
(v) =>
`${v.mag() > max ? "✅" : "❌"} limit(): ${v.toString()} ➝ ${v.limit(
max
)}`
);
return md`${logs.join(`<br>`)}`;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
task(
"1.6",
md`Referring back to the [Introduction](https://natureofcode.com/book/chapter-1-vectors/#intro_section6), implement acceleration according to Perlin noise.`
)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
class Mover {
constructor(p5) {
this.p5 = p5;
this.location = new P5.Vector(
this.p5.random(this.p5.width),
this.p5.random(this.p5.height)
);
this.velocity = new P5.Vector(this.p5.random(0.2), this.p5.random(0.2));
this.acceleration = P5.Vector.random2D().mult(p5.random(0.001, 1));
this.r = 10;
this.maxVelocity = 2;
}

update() {
this.edges();
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxVelocity);
this.location.add(this.velocity);
}

edges() {
if (this.location.x >= this.p5.width - this.r) {
this.location.x = this.p5.width - this.r - 1;
this.velocity.mult(-1);
this.acceleration.set(0, 0);
}
if (this.location.x <= this.r) {
this.location.x = this.r;
this.velocity.mult(-1);
this.acceleration.set(0, 0);
}
if (this.location.y >= this.p5.height - this.r) {
this.location.y = this.p5.height - this.r;
this.velocity.mult(-1);
this.acceleration.set(0, 0);
}
if (this.location.y <= this.r) {
this.location.y = this.r;
this.velocity.mult(-1);
this.acceleration.set(0, 0);
}
}

display() {
this.p5.fill("black");
this.p5.circle(this.location.x, this.location.y, this.r / 2);
this.p5.noFill();
this.p5.circle(this.location.x, this.location.y, this.r * 2);
}
}
Insert cell
Insert cell
Insert cell
import { task, intro } from "85dc677b160fa289"
Insert cell
import { P5, p5 } from "@tmcw/p5"
Insert cell
import { Walker, drawStart, height } from "3833326383d504e2"
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