代码之家  ›  专栏  ›  技术社区  ›  Samina

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

  •  0
  • Samina  · 技术社区  · 7 年前

    我正在用p5制作彩色“五彩纸屑”。并从数组中选择随机颜色。

    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);
    }
    

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   CRice    7 年前

    问题似乎是每次粒子移动时都会重新选择颜色。违规区域为:

    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);
            // ...
        }
        // ...
    }
    

    请注意,此颜色选择是 display 呼叫相反,我认为您应该在创建雨滴时选择一次颜色,然后在每次重新显示雨滴时使用相同的颜色。一种解决方案是在雨滴上添加颜色作为属性。例如,更改构造函数:

    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 与修复。

        2
  •  0
  •   Dan Oswalt    7 年前

    这对我很有用:

    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)