如何将椭圆的颜色更改为随机颜色

时间:2017-03-22 19:32:22

标签: javascript

我对Javascript new 并希望了解它。 youtube上有一个人有一个关于Javascript的教程,每次在教程结束时,他都会挑战我们在使用他在教程中经历的事情时稍微改变他的代码。他写了一个代码,当球撞到角落时球会反弹,他挑战我们每次弹跳时都会有一种新的颜色。

我设法编写了一个改变颜色的功能,但是只有在你输入(#)之前填充(200,0,200);"。但是,如果您删除了//并使用" fill(200,0,200);"它只显示颜色"粉红色"即使它在//之前"填充(200,0,200);"。

时会变为随机颜色

所以我的问题是。如何在保持" fill(200,0,200);"

的同时将椭圆更改为随机颜色

我已经尝试解决这个问题已经有一段时间了,但不会占上风。

var r,g,b;

var ball = {
 x: 300,
 y: 200,
 xspeed: 4,
 yspeed: -3
}

function setup() {
 createCanvas(600, 400);


}

function draw() {
 background(0);
 move();
 bounce();
 display();
 colorChange();
 r = random(255);
 g = random(255);
 b = random(255);

}



function bounce() {

 if (ball.x > width || ball.x < 0) {
  ball.xspeed = ball.xspeed * -1;
 }

 if (ball.y > height || ball.y < 0) {
  ball.yspeed = ball.yspeed * -1;
 }
}

function display() {
 stroke(255);
 strokeWeight(4);
 fill(200,0,200);
 ellipse(ball.x, ball.y, 24, 24);



}

function move() {
 ball.x = ball.x + ball.xspeed;
 ball.y = ball.y + ball.yspeed;

}


 function colorChange() {
  if (ball.x >= width || ball.x <= 0 || ball.y >= height || ball.y<= 0) {
    fill(r,g,b);
    ellipse();


  }



 }

1 个答案:

答案 0 :(得分:1)

问题中没有显示很多代码,所以我不能轻易地给你一个工作演示,我通常喜欢这样做,但一般来说,我要做的第一件事就是给球一个{ {1}}属性,因为那是属于球的东西:

color

这样就给了我们起始值。致var ball = { x: 300, y: 200, xspeed: 4, yspeed: -3, color: { r: 200, g: 0, b: 200 } // else you could use an array [200, 0, 200] } 的电话现在将更改为:

fill

我会调整fill(ball.color.r, ball.color.g, ball.color.b); // or if using the array: fill(ball.color[0], ball.color[1], ball.color[2]); 函数来更新球的颜色属性,如下所示:

colorChange

最后我们只想在弹跳时更改颜色,因此当检测到反弹(并且方向发生变化)时,触发此操作的最佳位置是现有代码:

function colorChange() {
  ball.color.r = random(255);
  ball.color.g = random(255);
  ball.color.b = random(255);
}

注意我已使用快捷方式编写function bounce() { if (ball.x > width || ball.x < 0) { ball.xspeed *= -1; colorChange(); } if (ball.y > height || ball.y < 0) { ball.yspeed *= -1; colorChange(); } } 。如果需要,您可以使用ball.yspeed = ball.yspeed * -1;等对move函数执行相同操作。

相关问题