xxxxxxxxxx
83
let font;
let sentence = "I am playing with P5JS";
let particles = [];
function preload() {
font = loadFont('Fuggles-Regular.ttf'); // Replace with the path to your font file
}
function setup() {
createCanvas(800, 400);
background(255);
// Create particles from each letter in the sentence
let points = font.textToPoints(sentence, 100, 200, 128);
for (let i = 0; i < points.length; i++) {
let pt = points[i];
let particle = new Particle(pt.x, pt.y);
particles.push(particle);
}
}
function draw() {
background(255);
for (let i = 0; i < particles.length; i++) {
let p = particles[i];
p.behaviors();
p.update();
p.show();
}
}
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = p5.Vector.random2D();
this.acc = createVector();
this.maxSpeed = 4;
this.prevPos = this.pos.copy();
}
behaviors() {
let target = createVector(mouseX, mouseY);
let arrive = this.arrive(target);
this.applyForce(arrive);
}
applyForce(f) {
this.acc.add(f);
}
arrive(target) {
let desired = p5.Vector.sub(target, this.pos);
let d = desired.mag();
let speed = this.maxSpeed;
if (d < 100) {
speed = map(d, 0, 100, 0, this.maxSpeed);
}
desired.setMag(speed);
let steer = p5.Vector.sub(desired, this.vel);
steer.limit(1);
return steer;
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
}
show() {
stroke(0);
strokeWeight(4);
line(this.pos.x, this.pos.y, this.prevPos.x, this.prevPos.y);
this.updatePrev();
}
updatePrev() {
this.prevPos.x = this.pos.x;
this.prevPos.y = this.pos.y;
}
}