nature-of-code/1. Vectors/6. Random Walker/sketch.js

63 lines
1.5 KiB
JavaScript

class Walker {
constructor(x = 0, y = 0) {
this.t = createVector(0, 10000)
this.position = createVector(x, y)
this.velocity = createVector(0, 0)
this.accelaration = createVector(0, 0)
this.topSpeed = 50
}
step() {
this.accelaration = createVector(
map(noise(this.t.x), 0, 1, -1, 1),
map(noise(this.t.y), 0, 1, -1, 1)
).normalize()
this.accelaration.mult(50)
const dt = deltaTime/1000
this.velocity.add(p5.Vector.mult(this.accelaration, dt))
this.velocity.limit(this.topSpeed)
this.position.add(p5.Vector.mult(this.velocity, dt))
this.t.add(createVector(dt, dt))
if (this.position.x < 0) {
this.position.x += width
}
if (this.position.x > width) {
this.position.x -= width
}
if (this.position.y < 0) {
this.position.y += height
}
if (this.position.y > height) {
this.position.y -= height
}
}
draw() {
stroke(0)
line(
this.position.x, this.position.y,
this.position.x + this.accelaration.x,
this.position.y + this.accelaration.y
)
circle(this.position.x, this.position.y, 20)
}
}
let walker
function setup() {
createCanvas(640, 240)
background(255)
walker = new Walker(width/2, height/2)
}
function draw() {
background(255)
walker.step()
walker.draw()
}