PDA

View Full Version : draw multiple spheres with for loop



thebigbo
05-10-2014, 02:53 PM
I can't seem to understand how multiple copies of same object are being drawn using array of objects. Below you see my draw() method:


void draw(GLfloat x, GLfloat y, GLfloat z)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,z);

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

Inside display() I call draw() 4 times using the for loop so that I get 4 spheres on screen as a result, but instead it only draws 1 sphere. What's wrong?

void display()
{
SolidSphere **spheres = createSpheres();
float const win_aspect = (float)win_width / (float)win_height;

glViewport(0, 0, win_width, win_height);

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(.6, 0, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

for (int i = 0; i < 4; i++)
{
spheres[i]->draw(posX,posY,posZ);
}
for (int i = 0; i < 4; i++)
{
delete spheres[i];
}

delete[] spheres;

glutSwapBuffers();
}
Can you please suggest how to improve this so that I get 4 spheres instead of 1?

Dan Bartlett
05-10-2014, 03:07 PM
You're passing in the same value for posX, posY & posZ each time you draw the sphere, so will be drawing on the same spot 4 times.

thebigbo
05-10-2014, 03:18 PM
I use random float generator for posX, posY and posZ, so it's actually different value with every call. Sorry for not mentioning this in the first post.

thebigbo
05-11-2014, 12:32 AM
Found the problem.:o