Estoy experimentando con partículas y he establecido una lista de 8 colores que crean formas aleatorias. Ahora siempre aparecen los 8 colores en las partículas, pero me gustaría tener un número aleatorio de colores (1 a 8) cada vez que ejecuto el script.
esta es la parte relevante del código:
let colors = [ "dodgerBlue", "red", "#fff200", "limeGreen", "slateGrey", "orange", "hotPink", " #080808" ]; const dpi = 100; let Particle = function(x, y) { this.x = getRandomInt(cw); this.y = getRandomInt(ch); this.coord = {x:x, y:y}; this.r = Math.min(getRandomInt(cw / dpi), 10 ); this.vx = (Math.random() - 0.5) * 100; this.vy = (Math.random() - 0.5) * 100; this.accX = 0; this.accY = 0; this.friction = Math.random() * 0.07 + 0.90; this.color = colors[Math.floor(Math.random() * 8)]; }¿Cómo puedo obtener una salida de número aleatorio en lugar del "8" de la última línea?
Yo haría tres cosas:
Baraja la matriz
Solo usaré el código aleatorio de esta respuesta :
/** * Shuffles array in place. * @param {Array} a items An array containing the items. */ function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; }Eliminar elementos de la matriz
La forma más fácil de hacer esto es con la función de corte. Simplemente haces array.slice(0, 3) y eso mantendría los primeros elementos. En su ejemplo, le gustaría aleatorizar el segundo número, asegurándose de que siempre sea 1 o más.
Sin codificar la longitud de la matriz
En su código hay un 8 para la longitud de la matriz. Eso podría mejorarse usando array.length porque manejará cualquier longitud y es más fácil de entender.
Ejemplo
Juntando eso daría:
/** * Shuffles array in place. ES6 version * @param {Array} a items An array containing the items. * https://stackoverflow.com/a/6274381/16584778 */ function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } var colours = [ "red", "green", "blue", "yellow", "black", "pink", "orange", "purple" ]; // randomise the order of the colours shuffle(colours); // keep some/all of the colours colours = colours.slice(0, 1 + Math.floor(Math.random() * colours.length)); // show the colours that we have kept document.write(colours.join(' ') + '<br/>'); // output dots using our chosen colours for (var n = 0; n < 200; n++) { document.write('<span style="color:' + colours[Math.floor(Math.random() * colours.length)] + '">■</span> '); }Math.floor() devuelve un número máximo menor o igual, por eso siempre tiene el mismo 8. Especifique sus requisitos y use esto en su última línea:
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }Esa función devolverá siempre un valor aleatorio en el diapasón especificado.
Array.prototype.random = function(){ return this[Math.floor(Math.random() * this.length)]; } let colors = [ "dodgerBlue", "red", "#fff200", "limeGreen", "slateGrey", "orange", "hotPink", " #080808" ]; // syntax use console.log(colors.random())