Change the changeColor
parameter to float
and instead of increment by 1
add some small value like 0.1
or smaller depends on how quick you want to change the colors and how often your event is firing.
case 't':
// code for color transition
changeColor += 0.025;
break;
Use linear interpolation to compute the color based on parameter changeColor
.
//---------------------------------------------------------------------------
GLfloat diffColors[9][4] =
{
{0.3, 0.8, 0.9, 1.0},
{1.0, 0.0, 0.0, 1.0},
{0.0, 1.0, 0.0, 1.0},
{0.0, 0.0, 1.0, 1.0},
{0.5, 0.5, 0.9, 1.0},
{0.2, 0.5, 0.5, 1.0},
{0.5, 0.5, 0.9, 1.0},
{0.9, 0.5, 0.5, 1.0},
{0.3, 0.8, 0.5, 1.0}
};
GLfloat changeColor=0.0; // This must be float !!!
//---------------------------------------------------------------------------
void set_color()
{
int i;
const int N=9; // colors in your table
const GLfloat n=N+1.0; // colors in your table + 1
float *c0,*c1,c[4],t;
// bound the parameter
t=changeColor; // I renamed it so I do nto need to write too much)
while (t>= n) t-=n;
while (t<0.0) t+=n;
i=floor(t);
changeColor=t; // update parameter
t-=i; // leave just the decimal part
// get neighboring colors to t
c0=diffColors[i]; i++; if (i>=N) i=0;
c1=diffColors[i];
// interpolate
for (i=0;i<4;i++) c[i]=c0[i]+((c1[i]-c0[i])*t);
//glColor4fv(c);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, c);
}
//---------------------------------------------------------------------------
so the idea is to dissect the changeColor
to integer and fractional/decimal part. The integer part tells you between which 2 colors in your table you are and the fractional part <0..1>
tells how far from the one color to the other one.
Linear interpolation of value x
between 2 values x0,x1
and parameter t=<0..1>
is like this:
x = x0 + (x1-x0)*t
If you look at the code above it does the same for c,c0,c1,t
... In order this to get working the first chunk of code where you add to the parameter starting with case 't':
must be executed repetitively like in timer ... and also invoke rendering. If it is just in some onkey handler that is called only once per key hit (no autorepeat) then it will not work and you need to implement the addition in some timer or on redraw event if you continuously redrawing screen... Again if not even that is happening you need to change the architecture of your app.