OpenGL绘制圆圈,奇怪的错误

时间:2010-11-28 05:34:23

标签: opengl geometry vertex-array

我不是数学家,但我需要画一个圆圈。

我的方法是使用别人的数学计算得到圆周上的所有点,并将它们变成三角扇。

我需要顶点数组中的顶点,没有立即模式。

圆圈确实出现了。但是,当我尝试覆盖圈子时,会发生奇怪的事情。它们只出现一秒然后消失。当我将鼠标移出窗口时,一个三角形从无处伸出。

这是班级:

class circle
{
    //every coordinate with have an X and Y
    private:
    GLfloat *_vertices;
    static const float DEG2RAD = 3.14159/180;

    GLfloat _scalex, _scaley, _scalez;
    int _cachearraysize;

    public:

    circle(float scalex, float scaley, float scalez, float radius, int numdegrees)
    {
       //360 degrees, 2 per coordinate, 2 coordinates for center and end of triangle fan
        _cachearraysize = (numdegrees * 2) + 4;

        _vertices = new GLfloat[_cachearraysize];
        for(int x= 2; x < (_cachearraysize-2); x = x + 2)
        {
            float degreeinRadians = x*DEG2RAD;
            _vertices[x] = cos(degreeinRadians)*radius;
            _vertices[x + 1] = sin(degreeinRadians)*radius;
        }


       //get the X as X of 0 and X of 180 degrees, subtract to get diameter.  divide
       //by 2 for radius and add back to X of 180
        _vertices[0]= ((_vertices[2] - _vertices[362])/2) + _vertices[362];

        //same idea for Y
        _vertices[1]= ((_vertices[183] - _vertices[543])/2) + _vertices[543];

        //close off the triangle fan at the same point as start
        _vertices[_cachearraysize -1] = _vertices[0];
        _vertices[_cachearraysize] = _vertices[1];

        _scalex = scalex;
        _scaley = scaley;
        _scalez = scalez;

    }
    ~circle()
    {
        delete[] _vertices;
    }

    void draw()
    {
        glScalef(_scalex, _scaley, _scalez);
        glVertexPointer(2,GL_FLOAT, 0, _vertices);
        glDrawArrays(GL_TRIANGLE_FAN, 0, _cachearraysize);
    }
};

1 个答案:

答案 0 :(得分:2)

这是一些丑陋的代码,我会说 - 很多神奇的数字等等。

尝试类似:

struct Point {
   Point(float x, float y) : x(x), y(y) {}
   float x, y;
};
std::vector<Point> points;
const float step = 0.1;
const float radius = 2;

points.push_back(Point(0,0));
// iterate over the angle array
for (float a=0; a<2*M_PI; a+=step) {
   points.push_back(cos(a)*radius,sin(a)*radius);
}
// duplicate the first vertex after the centre
points.push_back(points.at(1));

// rendering:

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2,GL_FLOAT,0, &points[0]);
glDrawArrays(GL_TRIANGLE_FAN,0,points.size());

您可以根据自己的喜好将其重写为课程。背后的数学很简单,不要害怕尝试去理解它。