如何在现代opengl中绘制圆柱体

How to draw cylinder in modern opengl

我的问题很简单,如何在现代 OpenGL 中绘制圆柱体?我将 GLFW 与 OpenGL 3.x 一起使用。起初我的想法是创建一个函数来计算底部和顶部的顶点位置作为圆,然后在这些顶点之间画线。但我不知道如何实现这个。有没有人有好的解决方案?

您可以使用三角形条带来做到这一点,并在底部生成一个顶点,然后在顶部生成一个顶点。那应该很容易产生侧面。然后只需用三角扇生成盖子就可以了。为了简化事情,您可以使用模型视图矩阵将圆柱体移动到您想要的位置。这样你只需要在 x/y 平面或类似的平面上有一个圆,所以数学很简单。

为了性能考虑使用预编译对象 and/or 顶点数组。

我已经使用它一段时间了,希望它能对以后的人有所帮助。

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;