xxxxxxxxxx
83
let maxSpeed = 2;
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.opos = createVector(x, y);
this.vel = createVector(0, 0);
}
display() {
circle(this.pos.x, this.pos.y, 5);
}
move() {
let acc = createVector(random(-1, 1), random(-1, 1));
this.vel.add(acc);
this.vel.limit(maxSpeed);
this.pos.add(this.vel);
}
wrap() {
if (this.pos.x > width) {
this.pos.x = 0;
}
if (this.pos.x < 0) {
this.pos.x = width;
}
if (this.pos.y > height) {
this.pos.y = 0;
}
if (this.pos.y < 0) {
this.pos.y = height;
}
}
avoid(snake) {
let dist = this.pos.dist(snake.pos);
let distoriginal = this.pos.dist(this.opos);
if (dist < 20) {
let steer = p5.Vector.sub(this.pos,snake.pos);
steer.mult(exp(20-dist));
this.vel.add(steer);
}
else if(distoriginal > 0.1 && dist > 25)
{
let steer = p5.Vector.sub(this.opos,this.pos);
this.vel.add(steer);
}
this.vel.limit(maxSpeed);
this.pos.add(this.vel);
this.vel = createVector(0,0);
}
}
let particles = [];
let numParticles = 500;
let snake;
function setup() {
createCanvas(400, 400);
for (let i = 0; i < numParticles; i++) {
particles[i] = new Particle(random(0, width), random(0, height));
}
snake = new Particle(width / 2, height / 2);
}
function draw() {
background(220);
for (let i = 0; i < numParticles; i++) {
fill(255);
particles[i].display();
particles[i].avoid(snake);
}
fill(255, 0, 0);
snake.display();
snake.move();
snake.wrap();
}