我怎样才能使我的立方体的面在彩虹的所有颜色之间平滑过渡?

How can I make the faces of my cube smoothly transition between all colors of the rainbow?

我在 Visual Studio 中有一个程序可以正确渲染缓慢旋转的 3D 立方体。我有一个有效的 FillTriangle() 函数,它用我输入的十六进制代码作为参数的任何颜色填充立方体的面(例如,紫色为 0x00ae00ff)。我已将每张脸的颜色设置为从红色 (0xFF000000) 开始,然后我在 main() 中有一个 while 循环来更新场景并在每一帧绘制新像素。我还有一个 Timer class 来处理各种与时间相关的事情,包括每帧更新事情的 Update() 方法。我想让脸的颜色平滑地从一种颜色过渡到另一种颜色,通过彩虹的每一种颜色,我希望它循环执行,只要程序是 运行。现在,它在几种颜色之间平稳过渡,然后突然跳到另一种颜色。例如,它可能从黄色平滑地过渡到橙色再到红色,但随后突然跳到绿色。这是现在正在执行的代码:

...
main()
{
...
float d = 0.0f; //float for the timer to increment

 //screenPixels is the array of all pixels on the screen, numOfPixels is the number of pixels being displayed
 while(Update(screenPixels, numOfPixels))
 {
   ...
   timer.Signal(); //change in time between the last 2 signals
   d += timer.Delta(); //timer.Delta() is the average current time
   if(d > (1/30))    // 1 divided by number of frames
   {
     //Reset timer
     d = 0.0f;
     
     //Add to current pixel color being displayed
     pixelColor += 0x010101FF;
   }
   ...
 }
 ...
}

有没有更好的方法来解决这个问题?添加到当前像素颜色是我想到的第一件事,它有点工作,但由于某种原因它一直在跳过颜色。

每次添加该常量都会溢出。不仅仅是一个整数,而是跨越色谱的每个组成部分:R、G 和 B。

您需要将 pixelColor 分成单独的红色、绿色和蓝色,并独立地对每个字节进行数学计算。并将 Alpha 固定为 255(完全不透明)。并沿途检查 overflow/underflow。当您到达上溢或下溢时刻时,只需将方向从递增更改为递减。

此外,我不会在每个步骤中将每个组件递增相同的值 (1)。在 R、G 和 B 上使用相同的增量,您只需向颜色添加“更多白色”。如果你想要一个更自然的彩虹循环,我们可以这样做:

改变这个:

 pixelColor += 0x010101FF;

为此:

 // I'm assuming pixelColor is RGBA

 int r = (pixelColor >> 24) & 0x0ff;
 int g = (pixelColor >> 16) & 0x0ff;
 int b = (pixelColor >> 8)  & 0x0ff;

 r = Increment(r, &redInc);
 r = Increment(g, &greenInc);
 g = Increment(g, &blueInc);

 pixelColor = (r << 24) | (g << 16) | (b << 8) | 0x0ff;

其中 redInc、greenInc 和 blueInc 在主 while 循环外定义和初始化如下:

int redInc = -1;
int greenInc = 2;
int blueInc = 4;

增量函数是这样的:

 void Increment(int color, int* increment)  {
     color += *increment;
     if (color < 0) {
         color = 0;
         *increment = (rand() % 4 + 1);
     } else if (color > 255) {
         color = 255;
         *increment = -(rand() % 4 + 1);
     }
 }

这应该以更自然的方式(从较暗到较亮再到较暗)循环显示颜色,并带有一点随机性,因此永远不会出现两次相同的图案。您可以通过在初始化时调整初始 colorInc 常量以及如何在 Increment 函数中更新 *increment 值来玩弄随机性。

如果您看到任何奇怪的颜色闪烁,很可能是您的字母字节位置错误。它可能是高字节,而不是低字节。类似地,一些系统将整数中的颜色排序为 RGBA。其他人做ARGB。很可能 RGB 被 BGR 翻转了。