如何从数组中选取一个随机值,而该值不会在 p5/javascript 中不断变化?

How to pick a random value from an array without the value constantly changing in p5/javascript?

我正在使用 p5.js 创建彩色 "confetti" 并从数组中选择随机颜色。

var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'purple', 'pink'];

我希望随机函数只选择一个,而不是一遍又一遍地遍历数组,使颜色发生变化。如果我将 confettiColor 变量放入设置中,它会使所有粒子都相同。换句话说,我如何从数组中为每个粒子选择一种随机颜色而不遍历它们?

else if (changeConfetti.checked) {
  //var confettiSize = random(1,8);

  confettiColor = colors[Math.floor(Math.random() * colors.length)];
  stroke(confettiColor);
  strokeWeight(3);
  line(this.x,this.y,this.x+5,this.y-10);
}

我的完整代码在 CodePen 上https://codepen.io/Fragile404/pen/gzbzXv

看来问题是每次粒子移动时颜色都会重新select。违规区域是:

rainDrop.prototype.display = function()
{
    if (changeSeason.checked)
    {
        // ...
    }
    else if (changeConfetti.checked)
    {
        //var confettiSize = random(1,8);

        confettiColor = colors[Math.floor(Math.random() * colors.length)];
        stroke(confettiColor);
        // ...
    }
    // ...
}

请注意,此颜色 selection 是 display 调用的一部分。相反,我认为您希望在创建雨滴时 select 一次颜色,然后在每次重新显示雨滴时使用相同的颜色。一种解决方案是将颜色作为 属性 添加到雨滴上。例如,更改构造函数:

var rainDrop = function()
{
    this.x = random(canvasWidth+1000);
    this.y = random(-100,-50);
    // Add this:
    this.confettiColor = colors[Math.floor(Math.random() * colors.length)];
};

然后在显示方法中引用该值:

stroke(this.confettiColor)

这是 a fork of your codePen 的修复。

这对我有用:

var rainDrop = function()
{
    this.x = random(canvasWidth+1000);
    this.y = random(-100,-50);
    this.confettiColor = colors[Math.floor(Math.random() * colors.length)]; 
};

然后在显示中,使用stroke(this.confettiColor);代替stroke(confettiColor)