nature-of-code/Ecosystem Project/sketch.js

119 lines
2.9 KiB
JavaScript

class Walker {
constructor(
position,
speed,
topSpeed,
trailSize,
color,
accelerationType,
headSize
) {
this.t = random(1000000)
this.position = position
this.velocity = createVector(0, 0)
this.acceleration = createVector(0, 0)
this.trail = []
this.trailSize = trailSize
this.speed = speed
this.topSpeed = topSpeed
this.color = color
this.accelerationType = accelerationType
this.headSize = headSize
}
step(dt) {
let dx = this.acceleration.x
let dy = this.acceleration.y
if (this.accelerationType == "noise") {
dx = map(noise(this.t), 0, 1, -1, 1)
dy = map(noise(this.t + 10000), 0, 1, -1, 1)
} else if (this.accelerationType == "random") {
if (random(0, 1) < 0.15) {
dx = random(-1, 1)
dy = random(-1, 1)
}
}
this.acceleration = createVector(dx, dy).normalize()
this.acceleration.setMag(this.speed)
this.velocity.add(p5.Vector.mult(this.acceleration, dt))
this.velocity.limit(this.topSpeed)
this.position.add(p5.Vector.mult(this.velocity, dt))
this.t += dt/2
this.position.x = (this.position.x + width) % width
this.position.y = (this.position.y + height) % height
this.trail.push(this.position.copy())
if (this.trail.length > this.trailSize) {
this.trail.splice(0, 1)
}
}
draw() {
stroke(this.color)
for (var p of this.trail) {
point(p)
}
circle(this.position.x, this.position.y, this.headSize)
// line(this.position.x, this.position.y, this.position.x+this.velocity.x, this.position.y+this.velocity.y)
}
}
let speedUp = 0
let creatures = []
let speedUpSlider
function setup() {
createCanvas(640, 240)
background(255)
for (let i = 0; i < 20; i++) {
creatures.push(new Walker(
createVector(random(0, width), random(0, height)),
10,
10,
200,
color(20, 200, 20),
"noise",
3
))
}
for (let i = 0; i < 50; i++) {
creatures.push(new Walker(
createVector(random(0, width), random(0, height)),
400,
50,
10,
color(20, 20, 20),
"random",
1
))
}
speedUpSlider = createSlider(0, 10, 0)
speedUpSlider.changed(() => {
speedUp = speedUpSlider.value()
})
}
function draw() {
background(255)
// let fps = frameRate();
// text(Math.round(fps), 50, 50);
let dt = deltaTime / 1000
for (let i = 0; i < speedUp + 1; i++) {
for (var creature of creatures) {
creature.step(dt)
creature.draw()
}
}
}