下面是指向我的项目的链接:https://editor.p5js.org/darkknightishaan/sketches/mXgN5Z_72
现在,我使用setup()函数创建画布,创建气泡。我尝试将Bubble变量声明在setup()函数之前和之后以及draw()函数和两个函数的外部移动到它自己的函数中。我还尝试将画布创建移到另一个部分,但这些解决方案都没有效果。我如何调整这段代码,使它每0.5秒在画布中创建一个新的气泡,而不是每2.9秒重置一次画布和气泡?
class Bubble {
constructor() {
let allInstances = [];
let radius = random(20, 200);
let red = random(210, 255);
let randRed = parseInt(red);
let alpha = random(0.25, 0.6);
let randAlpha = alpha.toFixed(2);
let color = `rgba(${randRed},255,255,${randAlpha})`;
this.x = random(100, 700);
this.y = random(100, 500);
this.width = radius;
this.height = radius;
this.color = color;
this.velocityX = random(-5, +5);
this.velocityY = random(-5, +5);
this.display = function() {
stroke(255);
fill(this.color);
ellipse(this.x, this.y, this.width, this.height);
}
this.move = function() {
this.x = this.x + this.velocityX;
this.y = this.y + this.velocityY;
}
}
}
/*
var bubbles = [];
function setup() {
createCanvas(800, 600);
bubble1 = new Bubble();
bubble2 = new Bubble();
bubble3 = new Bubble();
bubble4 = new Bubble();
bubble5 = new Bubble();
bubble6 = new Bubble();
}
function draw() {
background(56, 226, 232);
bubble1.move();
bubble2.move();
bubble3.move();
bubble4.move();
bubble5.move();
bubble6.move();
bubble1.display();
bubble2.display();
bubble3.display();
bubble4.display();
bubble5.display();
bubble6.display();
}
setInterval(function() {
setup();
draw();
}, 2900);
*/html,
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
<script src="Bubble.js"></script>
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
这是我的代码,注释的代码是我当前的JavaScript代码,它具有前面提到的setup()和绘图函数以及Bubble类。
发布于 2020-05-06 00:39:08
这里发生了很多事情,所以我要试着把这一切都看清楚。
首先,在使用p5库时,setup()是一个函数,在程序开始时调用,因此,对于良好的实践,您不应该调用它。其次,系统以每秒60次的速度调用draw()。您可以用framerate(put what every number you would like修改这个
现在,对于您的气泡,您要做的是使用一个for循环开始创建您的气泡。重新画他们。就像这样。为了创造。
for (i=0; i<numOfBubbles; i++) {
bubble[i] = new Bubble();
}然后让他们移动并画这个作品。
for (i=0; i<numOfBubbles; i++) {
bubble[i].move();
bubble[i].display();
}N0ow来制造一个新的气泡来代替这个
setInterval(function() {
setup();
draw();
}, 2900);如果不考虑,for循环对数字来说可能很有趣,因为它从迭代0开始,并且只有在小于5的情况下才上升到4。
function newbubble() {
bubble[numOfBubbles] = new Bubble();
numOfBubbles++
}
setInterval(newbubble, 2000);注意,您需要更好的变量。
var bubble = {};
// note this should be one less then what you want as for loops first iterations as at 0
var numOfBubbles = 5;另外,现在您已经阅读了所有这些解释,下面是代码https://editor.p5js.org/16340jt@hvhs.school.nz/sketches/qahzu3opJ
这应该会回答你的问题,但它或多或少地重写了你的程序,但如果你接受了这门课,它将在未来真正帮助你。
https://stackoverflow.com/questions/61589942
复制相似问题