How to draw cylinder in modern opengl

余生颓废 提交于 2019-12-12 17:54:21

问题


My question is simple, how do I draw a cylinder in modern OpenGL? I'm using GLFW together with OpenGL 3.x. My thought at first was to create a function that computes the vertex positions at the bottom and at the top as circles and then draw lines between these vertices. But I have no idea how to implement this.. Does anyone have a good solution?


回答1:


You can do that with a triangle strip and generate a vertex at the bottom then one at the top. That should generate the sides easily. Then just generate the caps with a triangle fan and you are don. To simplify things you can use the modelview matrix to move the cylinder into position where you want. This way you only need to have a circle in the x/y plane or similar so the math is very simple.

For performance consider using precompiled objects and/or vertex arrays.




回答2:


I have been using this for a while now and I hope it will help people in the future.

struct {
   GLfloat x,z, y_start, y_end;
}each_pole; // struct
std::vector<each_pole> each_pole_vector; // vector of structs

//Cylinder with y axis up
GLfloat cylinder_height = 1.0f,
        cylinder_radius = 0.5f,
        nr_of_points_cylinder = 360.f;

for (int i = 0; i < nr_of_points_cylinder; ++i)
{
    GLfloat u = i / (GLfloat)nr_of_points_cylinder;

    //Where the cylinder is in the x and z positions (3D space) 
    each_pole.x = center.x 
    + cylinder_radius*cos(2*M_PI*u); 
    each_pole.z = center.z 
    + cylinder_radius*sin(2*M_PI*u); 

    each_pole.y_start = 0.0f;
    each_pole.y_end = cylinder_height;

    each_pole_vector.push_back(each_pole);

}

return each_pole_vector;


来源:https://stackoverflow.com/questions/32883572/how-to-draw-cylinder-in-modern-opengl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!