Search code examples
c++openglglew

Drawing a circle using OpenGL C++


I want to draw a circle in a specific position using the coordinates of the centre of the circle and its radius. All the methods that i found are using glut and none of them position the circle in a specific point. I wanna mention that I'm new to this things and if I'm doing something wrong, I would be happy to know it. This is what I did so far:

class Constructor

Mesh::Mesh(Vertex * vertices, unsigned int numVertices) {
    m_drawCont = numVertices;
    glGenVertexArrays(1, &m_vertexArrayObject);
    glBindVertexArray(m_vertexArrayObject);

    glGenBuffers(NUM_BUFFERS, m_vertexArrayBuffers);
    glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[POSITION_VB]);

    //PUT ALL OF OUR VERTEX DATA IN THE ARRAY
    glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(vertices[0]), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindVertexArray(0);
}

Draw Circle Method

void Mesh::DrawCircle() {
    glBindVertexArray(m_vertexArrayObject);
    glDrawArrays(GL_LINE_LOOP, 0, m_drawCont);
    glBindVertexArray(0);
}

Main method

int main(int argc, char **argv) {
    Display display(800, 600, "Window1");
    Shader shader("./res/basicShader");
    Vertex vertices2[3000];

    for (int i = 0; i < 3000; i++) {
        vertices2[i] = Vertex(glm::vec3(cos(2 * 3.14159*i / 1000.0), sin(2 * 3.14159*i / 1000.0), 0));
    }

    Mesh mesh3(vertices2, sizeof(vertices2) / sizeof(vertices2[0]));

    while (!display.IsClosed()) {
        display.Clear(0.0f, 0.15f, 0.3f, 1.0f);
        shader.Bind();
        mesh3.DrawCircle();
        display.Update();
    }
}

And this is the output image


Solution

  • The code which actually creates circle vertices

    as cos(x) and sin(x) function returns values is [0..1] than multiplication to some value will give us circle with radios of that value. Adding or subtracting x and y values will move the center of the circle to a specific position. fragments value specifies detalization of circle greater-better.

    std::vector<Vertex> CreateCircleArray(float radius, float x, float y, int fragments)
    {
         const float PI = 3.1415926f;
    
         std::vector<Vertex> result;
    
         float increment = 2.0f * PI / fragments;
    
         for (float currAngle = 0.0f; currAngle <= 2.0f * PI; currAngle += increment)
         {
             result.push_back(glm::vec3(radius * cos(currAngle) + x, radius * sin(currAngle) + y, 0));
         }
    
         return result;
    }