# OpenGL/GLUT cylinder and cone

• 04-11-2011
software tester
OpenGL/GLUT cylinder and cone
I have been playing around with a piece of code for a cylinder in GLUT or OpenGL and using Vertices instead of pre-forms and the resulting code is below.

It is also capable of producing a cone and an offset cone with a small amount of modification. I hope that it will be of help to someone.

I apologise in advance if my identation is out but I cut and pasted various bits and changed other bits some many times that all correct layout went completely by the end.

I'm not sure how useful it will be for texture mapping as I haven't learnt that yet.

Code:

```glBegin( GL_TRIANGLE_FAN );     glNormal3f(0.0f,1.0f,0.0f);     //change y value here and in the vertex below to move the end up or     // down to seal the top end of the cylinder     glVertex3f(0.0f,6,0.0f);     for(i=0;i<=300;i++)     {         glVertex3f(2*cos(-i),6,2*sin(-i));     }     glEnd(); // bottom end of cylinder     glBegin( GL_TRIANGLE_FAN );     glNormal3f(0.0f,-1.0f,0.0f);     //change y value here and in the vertex below to move the end up or     // down to seal the bottom end of the cylinder. Delete for a cone     glVertex3f(0.0f,-0,0.0f);     for(i=0;i<=300;i++)     {         glVertex3f(2*cos(i),0,2*sin(i));     }     glEnd(); //side of cylinder, y-values are used for the length of the cylinder //x and z values are used for the radius. // for a cone change y values to integers for the length.     for(j=0;j<=45;j++){                         glBegin(GL_QUAD_STRIP);                         for(i=0;i<300;i++){                         glNormal3f(2*cos(i), 0.0f, 2*sin(i)); //  for a cone change the x and z values to 0 for a central cone or other integers for an offset cone // don't forget to delete the bottom end circle above.                         glVertex3f(2*cos(i), (j)/7, 2*sin(i));                         glVertex3f(2*cos(i), (j+1)/7, 2*sin(i));                         }     }     glEnd();```
• 04-11-2011
GReaper
GLU with its optimized support for quadrics can be very useful at drawing various shapes. Look it up.
• 04-11-2011
software tester
I tried it and eventually got it to work with quadrics and not crashing out codeblocks but I also tried this an alternative for more flexibility and no quadrics. Also for some reason I can't draw a cylinder in OpenGL without having the sphere in it as well. I must of done something wrong somewhere.
Also OpenGL won't draw an offset cone.

I'm trying to work on a sphere after I complete a ball bearing clock in GLUT.
• 04-13-2011
GReaper
Quote:

Originally Posted by software tester
Also for some reason I can't draw a cylinder in OpenGL without having the sphere in it as well.

What do you mean by that? :confused:
• 04-14-2011
software tester
Quote:

Originally Posted by Sipher
What do you mean by that? :confused:

Not entirely sure yet but I set up the quadrics etc and when I enter