Part of the Khronos Group
OpenGL.org

The Industry's Foundation for High Performance Graphics

from games to virtual reality, mobile phones to supercomputers

Results 1 to 4 of 4

Thread: draw multiple spheres with for loop

  1. #1
    Junior Member Newbie
    Join Date
    May 2014
    Posts
    6

    draw multiple spheres with for loop

    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:

    Code :
    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?
    Code :
    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?
    Last edited by thebigbo; 05-10-2014 at 03:00 PM.

  2. #2
    Member Regular Contributor
    Join Date
    Aug 2008
    Posts
    445
    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.

  3. #3
    Junior Member Newbie
    Join Date
    May 2014
    Posts
    6
    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.

  4. #4
    Junior Member Newbie
    Join Date
    May 2014
    Posts
    6
    Found the problem.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •