随时间改变球体的颜色(处理)

Changing color of sphere with time (processing)

我是一个新的处理编码器,因为这个原因请温柔。 通常我的代码更长更复杂,但我为你写了一个简单的代码,我可以在我的代码上进行调整:

int speed = 1;
int x, z = 50;

void setup() {
  size(400, 400, P3D);
}

void draw() {
  background(0);
  noStroke();
  lights();
  translate(x, height/2, z);
  fill(255,0,0);
  sphere(25);

  if (x > width -50)
    noLoop();

  x += speed;
}

因此,如您所见,球体以红色开始并到达 window 的末端。我想将它的颜色从红色更改为白色,这需要 30 秒。到达 window 的末尾。但是我不知道如何。如果你帮助我,我会很高兴。 注意:我尝试了 lerpColor 函数但没有帮助我。

我认为这样的方法可行:

int r=255,b=255,g=255;

...

void draw(){
...

  int percent=x/width*100;
  fill(r,b*percent,g*percent)
  sphere(25)

...
}

所以球体只会在屏幕左侧为红色,在右侧为白色

数学是秘密。经常是。

您需要跟踪几件事才能完成此操作:穿过屏幕所需的时间(您说的是 30 秒)、球体的速度、颜色变化的速度.

在我们开始之前,我建议您使用 float 作为变量,即位置和速度。整数可以完成这项工作,但在某些时候,当您需要精度时,您可能会后悔没有使用浮点数或类似类型。

有两种方法可以处理随时间的变化:您可以计算时间并将需要绘制的内容绘制在应该绘制的位置,或者计算在一定时间内将绘制多少帧并移动内容因此。第一种技术的优点是即使系统延迟也能够在它们应该在的地方绘制东西(如果不能遵守它,处理将降低帧率),而第二种技术通常更容易使用。我们将采用帧率技术,因为这不应该很复杂,而且因为大多数程序不需要太多资源而会降低帧率。

Processing 中的帧速率也是主循环(draw() 循环)运行 的速率。所以我们将选择一个帧率,它可以让我们计算球体的速度和颜色变化的速度。剩下的就是看着它移动。

这是您的示例,但经过修改使其大致按照您所说的工作:

float speed;
float x, z = 50;
float greenBlueStrength = 0;
float colorFadeRate = 1;
int fadeTimeInFrames;

void setup() {
  size(400, 400, P3D);
  frameRate(60); // 60 is the default framerate per second
  // so 30 seconds == (30*60) == 1800 frames
  // so you must have the speed to match
  fadeTimeInFrames = 60 * 30;
  speed = (width - 50) / (float)fadeTimeInFrames;
  colorFadeRate = 255 / (float)fadeTimeInFrames;
  println(colorFadeRate);
}

void draw() {
  background(0);
  textSize(30);
  text((millis()/1000) + " s. // color: " + (int)greenBlueStrength, 20, 50);
  // this is just to keep track of changes while they happen

  noStroke();
  lights();
  translate(x, height/2, z);
  fill(255, greenBlueStrength, greenBlueStrength);
  sphere(25);

  if (x > width -50) {
    noLoop();
  } // no actual change, but use brackets anyway, it's easier to read

  // updating what needs to be updated
  x += speed;
  greenBlueStrength += colorFadeRate;
}

我会在附近闲逛,如果您有任何问题,请不要犹豫。

玩得开心!