Skip to content

Instantly share code, notes, and snippets.

@gomako
Created June 11, 2018 08:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gomako/b159465eca101a1588f40d11dbfe31c0 to your computer and use it in GitHub Desktop.
Save gomako/b159465eca101a1588f40d11dbfe31c0 to your computer and use it in GitHub Desktop.
Draw a cylinder or cone in Processing
// Originally found at https://forum.processing.org/one/topic/draw-a-cone-cylinder-in-p3d.html
void cylinder(float bottom, float top, float h, int sides)
{
pushMatrix();
translate(0,h/2,0);
float angle;
float[] x = new float[sides+1];
float[] z = new float[sides+1];
float[] x2 = new float[sides+1];
float[] z2 = new float[sides+1];
//get the x and z position on a circle for all the sides
for(int i=0; i < x.length; i++){
angle = TWO_PI / (sides) * i;
x[i] = sin(angle) * bottom;
z[i] = cos(angle) * bottom;
}
for(int i=0; i < x.length; i++){
angle = TWO_PI / (sides) * i;
x2[i] = sin(angle) * top;
z2[i] = cos(angle) * top;
}
//draw the bottom of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, -h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
}
endShape();
//draw the center of the cylinder
beginShape(QUAD_STRIP);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
vertex(x2[i], h/2, z2[i]);
}
endShape();
//draw the top of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x2[i], h/2, z2[i]);
}
endShape();
popMatrix();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment