PAFF
PAFF

Reputation: 3

Chancing the color of a random chosen object from an array

I am making a top view bird game, and trying to change the color of only one of the chosen element from the array. I am pretty new to JavaScript and general. I think I did the choosing part correct, but whatever I do, couldn't manage to change the color. I am only stuck with changing the color part, so didn't include the rest of the code. Cheers!

//Drawing the basic bird shape
function drawBird(ctx, bird) {
const angle = Math.atan2(bird.dy, bird.dx);
ctx.translate(bird.x, bird.y);
ctx.rotate(angle);
ctx.translate(-bird.x, -bird.y);
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.moveTo(bird.x, bird.y);
ctx.lineTo(bird.x - 30, bird.y + 10);
ctx.lineTo(bird.x - 30, bird.y - 10);
ctx.lineTo(bird.x, bird.y);
ctx.fill();
ctx.setTransform(1, 0, 0, 1, 0, 0);}

//Choosing one of the elements of the array
const randomElement = birds[Math.floor(Math.random() * birds.length)];

//Here suppose to be changing the color

Upvotes: 0

Views: 35

Answers (1)

Husky Slava
Husky Slava

Reputation: 81

You can add a color parameter to your drawBird function and run it again after randomly choosing a bird

//Drawing the basic bird shape
function drawBird(ctx, bird, color) {
const angle = Math.atan2(bird.dy, bird.dx);
ctx.translate(bird.x, bird.y);
ctx.rotate(angle);
ctx.translate(-bird.x, -bird.y);
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(bird.x, bird.y);
ctx.lineTo(bird.x - 30, bird.y + 10);
ctx.lineTo(bird.x - 30, bird.y - 10);
ctx.lineTo(bird.x, bird.y);
ctx.fill();
ctx.setTransform(1, 0, 0, 1, 0, 0);
}

//Choosing one of the elements of the array
const randomElement = birds[Math.floor(Math.random() * birds.length)];

//Here suppose to be changing the color

drawBird(ctx, randomElement, "purple");

Upvotes: 1

Related Questions