xxxxxxxxxx
202
const rad = 10;
const sep = 0.4;
const maxspeed = 3;
const predspeed = 4;
const maxforce = 0.2;
let pts;
class Thing {
constructor(predator) {
this.pos = createVector(random(width), random(height));
this.v = createVector(0, 0);
this.a = createVector(0, 0);
this.pred = predator;
}
steer() {
// Aim for the centre of the sketch
const t = createVector();
if (this.pred) {
let mp = null;
let md = 10000;
for (let th of pts) {
if (!th.pred && th.pos.x >= 0 && th.pos.x < width && th.pos.y >= 0 && th.pos.y < height ) {
const d = p5.Vector.dist(this.pos, th.pos);
if (d < md) {
md = d;
mp = th.pos;
}
}
}
t.x = mp.x;
t.y = mp.y;
} else {
t.x = width / 2;
t.y = height / 2;
}
const d = p5.Vector.dist(this.pos, t);
const v = p5.Vector.sub(t, this.pos);
v.setMag(maxspeed);
if (d < 50) {
v.setMag((maxspeed * d) / 50);
}
const a = p5.Vector.sub(v, this.v);
a.limit(maxforce);
this.a.add(a);
}
avoid() {
const v = createVector(0, 0);
let count = 0;
for (let th of pts) {
if (!th.pred) {
continue;
}
const d = p5.Vector.sub(this.pos, th.pos);
const m = d.mag();
if (m <= 40) {
d.setMag(1 / m);
v.add(d);
++count;
}
}
if (count > 0) {
v.div(count);
v.setMag(maxspeed);
const a = p5.Vector.sub(v, this.v);
a.mult(3.0);
a.limit(maxforce);
this.a.add(a);
}
}
separate() {
const v = createVector(0, 0);
let count = 0;
for (let th of pts) {
if (th === this) {
continue;
}
const d = p5.Vector.sub(this.pos, th.pos);
const m = d.mag();
if (m <= 15) {
d.setMag(1 / m);
v.add(d);
++count;
}
}
if (count > 0) {
v.div(count);
v.setMag(maxspeed);
const a = p5.Vector.sub(v, this.v);
a.mult(1.5);
a.limit(maxforce);
this.a.add(a);
}
}
align() {
const p = createVector(0, 0);
let count = 0;
for (let th of pts) {
if (th === this) {
continue;
}
const d = p5.Vector.dist(this.pos, th.pos);
if (d < 30) {
p.add(th.v);
++count;
}
}
if (count > 0) {
p.div(count);
p.setMag(maxspeed);
const a = p5.Vector.sub(p, this.v);
a.limit(maxforce);
this.a.add(a);
}
}
tick() {
this.a.x = 0;
this.a.y = 0;
if (this.pred) {
this.steer();
} else {
this.steer();
this.separate();
this.align();
this.avoid();
}
this.v.add(this.a);
this.v.limit(maxspeed);
this.pos.add(this.v);
}
draw() {
if (this.pred) {
fill(255, 0, 0);
} else {
fill(255, 255, 0);
}
circle(this.pos.x, this.pos.y, 10);
}
}
function init() {
N = 150;
pts = [];
for (let idx = 0; idx < N; ++idx) {
pts.push(new Thing(false));
}
pts.push(new Thing(true));
}
function tick() {
for (let th of pts) {
th.tick();
}
}
function setup() {
createCanvas(480, 480);
init();
}
function draw() {
background(0, 0, 100);
fill(255, 255, 0);
noStroke();
for (let p of pts) {
p.draw();
}
tick();
}
function keyPressed()
{
if( key === "s" ) {
save( "jan19.png" );
}
}