xxxxxxxxxx
75
const particles = [];
function setup() {
createCanvas(600, 400);
textAlign(CENTER, CENTER);
textSize(20);
textFont("monospace");
// particles.push(new Charge(-width / 4, 0, 1));
// particles.push(new Charge(width / 4, 0, -1));
createButton("+").mousePressed(() => {
particles.push(
new Charge(
random(-width / 2, width / 2),
random(-height / 2, height / 2),
1
)
);
});
createButton("-").mousePressed(() => {
particles.push(
new Charge(
random(-width / 2, width / 2),
random(-height / 2, height / 2),
-1
)
);
});
}
function mouseReleased() {
particles.forEach((p) => (p.dragging = false));
}
function draw() {
background(255);
translate(width / 2, height / 2);
for (let x = -width / 2; x < width / 2; x += 30) {
for (let y = -height / 2; y < height / 2; y += 30) {
push();
const field = particles
.map((p) => p.forceAt(x, y))
.reduce((acc, val) => acc.add(val), createVector(0, 0));
translate(x, y);
rotate(field.heading());
line(-10, 0, 10, 0);
translate(10, 0);
rotate(-PI / 2);
triangle(-2, 0, 2, 0, 0, 4);
pop();
}
}
const m = mouse();
particles.forEach((p) => {
p.draw();
p.update();
});
for (const p of particles) {
if (!p.dragging && mouseIsPressed && p.pos.dist(m) < 10) {
p.dragging = true;
break;
}
}
}
p5.prototype.mouse = function () {
return createVector(
this.mouseX - this.width / 2,
this.mouseY - this.height / 2
);
};