如何在Windows电脑上运行p5.js粒子树代码
这篇文章将引导您如何在Windows电脑上运行一段使用p5.js库绘制的粒子树代码。
您需要安装p5.js库和一个浏览器来运行这段代码。
- 下载p5.js库。您可以在官网 https://p5js.org/ 上下载最新版的p5.js库,也可以使用CDN链接,例如:
<script src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js'></script>
- 创建一个HTML文件,并在文件中引入p5.js库和sketch.js文件(包含上述代码)。
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Particle Tree</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js'></script>
<script src='sketch.js'></script>
</head>
<body>
</body>
</html>
- 在浏览器中打开这个HTML文件,就可以看到运行结果了。您可以在sketch.js文件中修改代码,实时预览效果。
以下是代码示例:
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(0, 0);
}
update() {
this.pos.add(this.vel);
}
}
class Node {
constructor(x, y, particle) {
this.pos = createVector(x, y);
this.particle = particle;
this.children = [];
}
addChild(child) {
this.children.push(child);
}
}
class Tree {
constructor(x, y, particle) {
this.root = new Node(x, y, particle);
}
addNode(parent, child) {
parent.addChild(child);
}
}
let tree;
let particles = [];
function setup() {
createCanvas(400, 400);
let rootParticle = new Particle(width / 2, height);
tree = new Tree(width / 2, height, rootParticle);
particles.push(rootParticle);
}
function draw() {
background(220);
let newParticles = [];
for (let i = 0; i < particles.length; i++) {
let particle = particles[i];
// 施加向上的力
particle.vel.add(createVector(0, -0.1));
// 更新粒子位置
particle.update();
if (particle.vel.mag() < 1) {
// 生成新的粒子作为子节点
let childParticle = new Particle(particle.pos.x, particle.pos.y);
let childNode = new Node(particle.pos.x, particle.pos.y, childParticle);
tree.addNode(tree.root, childNode);
// 将速度清零
particle.vel.mult(0);
childParticle.vel.mult(0);
newParticles.push(childParticle);
}
}
particles = particles.concat(newParticles);
// 绘制树
stroke(0);
noFill();
drawTree(tree.root);
}
function drawTree(node) {
for (let i = 0; i < node.children.length; i++) {
let child = node.children[i];
line(node.pos.x, node.pos.y, child.pos.x, child.pos.y);
drawTree(child);
}
}
希望这篇文章对您有所帮助。如果您有任何问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/oj6w 著作权归作者所有。请勿转载和采集!