p5js/demo_particle.js

107 lines
2.9 KiB
JavaScript
Raw Normal View History

2022-12-12 12:04:55 +00:00
let particles = [];
function setup() {
createCanvas(600, 600);
angleMode(DEGREES);
frameRate(60);
noStroke();
noCursor();
}
function draw() {
2022-12-12 15:04:46 +00:00
火把();
// 落珠();
2022-12-12 12:04:55 +00:00
}
2022-12-12 15:04:46 +00:00
function 火把() {
2022-12-12 12:04:55 +00:00
background(0);
2022-12-12 15:04:46 +00:00
drawGrid();
2022-12-12 12:04:55 +00:00
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;
2022-12-12 15:04:46 +00:00
p.life = 1;
2022-12-12 12:04:55 +00:00
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];
2022-12-12 15:04:46 +00:00
noiseDetail(2, 0.5);
let windForce = map(noise(frameCount / 1000), 0, 1, -500, 500);
// let windForce = map(mouseX, 0, width,-1000,1000)
p.applyForce(createVector(windForce, 0));
2022-12-12 12:04:55 +00:00
p.applyForce(createVector(0, -100));
2022-12-12 15:04:46 +00:00
p.move();
2022-12-12 12:04:55 +00:00
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();
2022-12-12 15:04:46 +00:00
textInfo("火把", "2022/12/11");
}
function 落珠() {
background(0);
drawGrid();
const x = mouseIsPressed ? mouseX : 300;
const y = mouseIsPressed ? mouseY : 50;
// 添加新粒子
if (particles.length < 1) {
for (let i = 0; i < 1; i++) {
const p = new Particle(x, y);
p.velocity.x = random(-50, 50);
p.life = 5;
particles.push(p);
}
}
push();
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.applyForce(createVector(0, 100));
p.move(true);
if (p.finished) {
particles.splice(i, 1);
} else {
const alpha = map(p.duration, 0, p.life, 255, 0);
stroke(255, alpha);
fill(128, alpha);
circle(p.position.x, p.position.y, 4);
}
}
pop();
textInfo("落珠", "2022/12/12");
}
function drawGrid() {
push();
stroke(255, 64);
strokeWeight(1);
for (let x = 0; x < width; x += 10) line(x, 0, x, height);
for (let y = 0; y < height; y += 10) line(0, y, width, y);
pop();
}
function textInfo(title, date, name = "赵海洋爸爸") {
push();
noStroke();
fill(255);
text(`作品:${title}`, 30, height - 70);
text(`作者:${name}`, 30, height - 50);
text(`日期:${date}`, 30, height - 30);
pop();
2022-12-12 12:04:55 +00:00
}