p5js/demo_particle.js
2022-12-12 20:04:55 +08:00

51 lines
1.2 KiB
JavaScript

let particles = [];
function setup() {
createCanvas(600, 600);
angleMode(DEGREES);
frameRate(60);
noStroke();
noCursor();
}
function draw() {
torch();
}
/**
* 火把
*/
function torch() {
background(0);
const x = mouseIsPressed ? mouseX : 300;
const y = mouseIsPressed ? mouseY : 500;
// 添加新粒子
for (let i = 0; i < 5; i++) {
const p = new Particle(x, y);
p.velocity.x = random(-1, 1) * 30;
p.velocity.y = random(-5, -1) * 50;
particles.push(p);
}
// 绘制火把
fill("lightgray");
rect(x - 5, y - 10, 10, 80);
fill("gray");
rect(x - 7, y - 10, 14, 20);
// 更新并绘制所有粒子
push();
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.applyForce(createVector(0, -100));
p.update();
if (p.finished) {
particles.splice(i, 1);
} else {
const alpha = map(p.duration, 0, p.life, 255, 0);
const size = map(p.duration, 0, p.life, 8, 32);
fill(255, alpha);
circle(p.position.x, p.position.y, size);
}
}
pop();
}