Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a color to random in OpenGL?

Tags:

opengl

I've tried countless times to try and get this to work. I've moved loads of it around but still, nothing works. When I press the M key, my lights are meant to change to random colours. However, they change just to white.

This is what i have...

float colorArray[100][3]; // Create an array for random colors

keyPressed function:

    case 'm' | 'M':
        updateLights(2);
    break;

defined_to_openGL function:

for (int i = 0; i < 3; i++)
{

    glPushMatrix();
    glColor3f(colorArray[i][0],colorArray[i][1],colorArray[i][2]);
        glTranslatef(-50*i/2,-20,0.5); // Begin the first circle at -50, -20. Then multiply by i to create a space between them.
        drawLights(2.0f);
    glPopMatrix();

    if(i <= 3)
    {
        glPushMatrix();
        glColor3f(colorArray[i][0],colorArray[i][1],colorArray[i][2]);
            glTranslatef(-38,-20,0.5);
            drawLights(2.0f);
        glPopMatrix();

        glPushMatrix();
        glColor3f(colorArray[i][0],colorArray[i][1],colorArray[i][2]);
            glTranslatef(-12,-20,0.5);
            drawLights(2.0f);
        glPopMatrix();
    }

}

Update lights function:

{
    cout << "update lights" << endl;
    for(int i = 0; i < 3; i++)
    {
        colorArray[i][0] = rand() % 255;
        colorArray[i][1] = rand() % 255;
        colorArray[i][2] = rand() % 255;
        glutPostRedisplay();
    }

}
like image 299
Daniel Nelson Avatar asked Dec 02 '25 15:12

Daniel Nelson


1 Answers

You are using glColor3f which accepts 3 float parameters in [0.0,1.0] for each color intensity while rand()%255 produces an output which is in [0,254].

You can either switch to glColor3ub( GLubyte red, GLubyte green, GLubyte blue) which accepts an unsigned byte (and change modulo to %256 since you are skipping a value with 255) or generate a value in [0.0,1.0]by changing your random generation to rand()/((float)RAND_MAX+1) but this mean that you will have to change the type of colorArray to GLFloat.

like image 85
Jack Avatar answered Dec 05 '25 01:12

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!