samedi 4 juin 2022

Generate Infinite Colors for Array

I want to create an array full of random colors, that will never run out to generate random balls with random colors. So instead of having only 5 colors (blue, red, green, yellow, white) to choose from I want a different color for every ball.

whole code:

I have already tried:

var randomColor = Math.floor(Math.random()*16777215).toString(16);

Here I only get one random color for every ball. And I have also used loops already which is probably the right answer but I just implemented it wrongfully.

JS:

var ballArray = [];
var colorArray = ['blue','red','green','yellow','white'];
var gravity = 0.9;

function drawBall() {
    for (var i = 0; i < ballArray.length; i++) {
        var ball = ballArray[i];
        ctx.fillStyle = ball.color;
        ctx.beginPath();
        ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
        
        ball.x += ball.xd;
        if (ball.x + ball.radius > screenWidth || ball.x - ball.radius < 0) {
            ball.xd *= -1;
        }



Aucun commentaire:

Enregistrer un commentaire