For a 2D asteroid game I'm trying to draw random polygons which would rotate at different speeds. I thought of generating the variables "vertex" , "xaxis", "yaxis" and radius using rand() function. But the problem is when I'm drawing them and rotating the seems to be continuously happening. like it draws a different polygon each time it rotates.
This is how I draw polygons by selecting vertices around the circumference of an imaginary circle.
void spinAsteroid(bool zaxis, GLfloat rotation, GLfloat radius, GLfloat xpos, GLfloat ypos, bool multiplyMatrix, int speed)
{
GLfloat z;
z = 0.0;
int vertexRand = (rand() % 9) + 1;
int vertex = vertexRand;
if (zaxis)z = 1.0;
if (!multiplyMatrix) {
glLoadIdentity();
}
glTranslatef(xpos, ypos, 0);
glRotatef(rotation, 0, 0, z);
glTranslatef(-xpos, -ypos, 0);
drawAsteroid(radius, vertex, xpos, ypos);
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
//glPushMatrix();
if(value!=7){ translatePattern(); }
//glPopMatrix();
//glPushMatrix();
int count = 0;
while(count<11){
int randIndex = rand() % 10;
int vertexRand = (rand() % 9) + 1;
spinAsteroid(true, angle, radius[randIndex], xaxis[randIndex], yaxis[randIndex], false, 2);
count++;
}
I just want to draw random polygons at different positions which would rotate.
Operations like glTranslate
and glRotate
define a transformation matrix and multiply the current matrix be the new matrix.
If you do multiply transformations in a row, then the transformations are concatenated with the previous transformations.
For individual transformations for each asteroid you've to store the current matrix, before the transformations for the asteroid are applied and restore the current matrix after the asteroid is drawn.
Since Legacy OpenGL matrices are organized on a stack, this can be achieved by push and pop the current matrix (see glPushMatrix
/ glPopMatrix
).
Furthermore you've to set an array of random points and radii, but you've to draw them in the same order in each frame.
e.g.:
void spinAsteroid(GLfloat rotation, GLfloat radius, GLfloat xpos, GLfloat ypos, int vertex, int speed)
{
glPushMatrix();
glTranslatef(xpos, ypos, 0);
glRotatef(rotation, 0, 0, 1.0f);
glTranslatef(-xpos, -ypos, 0);
drawAsteroid(radius, vertex, xpos, ypos);
glPopMatrix();
}
for(int i = 0; i < 10; ++i)
{
spinAsteroid(angle, radius[i], xaxis[i], yaxis[i], i+1, 2);
}