xxxxxxxxxx
123
var particles = [];
var fishs = [];
var t = 0;
var den = 50;
function preload() {
img = loadImage("seaBottom.png");
fishPic = loadImage("fish.png");
}
function setup() {
createCanvas(500, 500);
img.resize(width, height);
img.loadPixels();
let delta = width / den;
for (let i = 0; i < width; i += delta) {
for (let j = 0; j < height; j += delta) {
let color = img.get(i, j);
particles.push(new Particle(i, j, color[0], color[1], color[2]));
}
}
}
function draw() {
background(0, 30);
imageMode(CORNER);
tint(255, 8);
image(img, 0, 0);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].display();
}
for (let i = 0; i < fishs.length; i++) {
fishs[i].update();
if (
fishs[i].p.x > width ||
fishs[i].p.x < 0 ||
fishs[i].p.y > height ||
fishs[i].p.y < 0
) {
fishs.splice(i, 1);
}
}
}
class Particle {
constructor(x, y, r, g, b) {
this.pos = createVector(x, y);
this.target = this.pos.copy();
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.rad = 5;
this.r = r;
this.g = g;
this.b = b;
this.x = x;
this.y = y;
}
update() {
this.attraction = p5.Vector.sub(this.target, this.pos).mult(0.05);
this.repulsion = createVector(0, 0);
for (let k = 0; k < fishs.length; k++) {
this.fishForce = p5.Vector.sub(fishs[k].p, this.pos);
this.repulsion.add(this.fishForce);
}
this.repulsion.normalize();
this.vel.add(this.repulsion.mult(-2.5));
this.vel.add(this.attraction);
this.vel.limit(3);
this.vel.mult(0.7);
this.pos.add(this.vel);
}
display() {
push();
noStroke();
fill(this.r, this.g, this.b);
circle(this.pos.x, this.pos.y, this.rad);
pop();
}
}
class Fish {
constructor(x, y, na, nb) {
this.p = createVector(x, y);
this.vel = createVector(na, nb);
this.r = atan(nb / na);
this.deg = degrees(this.r);
this.deg = (this.deg + 360) % 360;
if (na < 0) {
this.deg += 180;
}
this.acc = createVector(0, 0);
this.hp = 255;
}
update() {
this.vel.add(this.acc);
this.p.add(this.vel);
push();
translate(this.p.x, this.p.y);
rotate(radians(this.deg));
noStroke();
tint(255, 255);
imageMode(CENTER);
fishPic.resize(50, 0);
image(fishPic, 0, 0);
//circle(this.p.x, this.p.y, 20);
pop();
}
}
function mousePressed() {
let va = random(-1, 1);
let vb = random(-1, 1);
let intensity = random(1.5, 4);
fishs.push(new Fish(mouseX, mouseY, va * intensity, vb * intensity));
}