p5 对象在移动数组后呈现奇怪
p5 object renders weirdly after shifting an array
在 this 笔中,我遇到的问题是数组中的最后一个球瞬间没有显示。我相信那是因为在移动数组时,对象必须重新渲染,但我似乎找不到解决此问题的解决方案。
function draw() {
background(0);
noStroke();
console.log(balls);
balls.forEach((i) => {
i.show();
i.radius += 1;
i.opacity -= 1;
if (i.opacity == 150) {
let newBall = new Ball(canvas.width/2, canvas.height/2, size, opacity);
balls.push(newBall);
}
if (i.opacity == 0) {
balls.shift();
}
});
在使用 forEach()
函数迭代数组时,不应在数组中添加或删除对象。
来自 MDN:
The range of elements processed by forEach()
is set before the first invocation of callback
. Elements that are appended to the array after the call to forEach()
begins will not be visited by callback
. If the values of existing elements of the array are changed, the value passed to callback
will be the value at the time forEach()
visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()
) during the iteration, later elements will be skipped
换句话说,仔细想想这个 if
语句在做什么:
if (i.opacity == 0) {
balls.shift();
}
在这里,您检查 i
(current 球)的不透明度是否为零,如果是,则首先删除 球。这几乎肯定不是您想要做的。
谷歌搜索 "javascript modify array during forEach" 将 return 大量结果。提示:您可以考虑将其分为两个步骤:一个循环遍历数组并添加新球,另一个步骤循环遍历数组并移除您想要删除的球。基本 for
循环会让你走得很远。
在 this 笔中,我遇到的问题是数组中的最后一个球瞬间没有显示。我相信那是因为在移动数组时,对象必须重新渲染,但我似乎找不到解决此问题的解决方案。
function draw() {
background(0);
noStroke();
console.log(balls);
balls.forEach((i) => {
i.show();
i.radius += 1;
i.opacity -= 1;
if (i.opacity == 150) {
let newBall = new Ball(canvas.width/2, canvas.height/2, size, opacity);
balls.push(newBall);
}
if (i.opacity == 0) {
balls.shift();
}
});
在使用 forEach()
函数迭代数组时,不应在数组中添加或删除对象。
来自 MDN:
The range of elements processed by
forEach()
is set before the first invocation ofcallback
. Elements that are appended to the array after the call toforEach()
begins will not be visited bycallback
. If the values of existing elements of the array are changed, the value passed tocallback
will be the value at the timeforEach()
visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. usingshift()
) during the iteration, later elements will be skipped
换句话说,仔细想想这个 if
语句在做什么:
if (i.opacity == 0) {
balls.shift();
}
在这里,您检查 i
(current 球)的不透明度是否为零,如果是,则首先删除 球。这几乎肯定不是您想要做的。
谷歌搜索 "javascript modify array during forEach" 将 return 大量结果。提示:您可以考虑将其分为两个步骤:一个循环遍历数组并添加新球,另一个步骤循环遍历数组并移除您想要删除的球。基本 for
循环会让你走得很远。