2 Pluspunkte 0 Minuspunkte

Wie kann ich mit OpenGL und GLFW einen einfachen Kreis zeichnen?

#include <GLFW/glfw3.h>
#include <math.h>

void drawCircle(float centerX, float centerY, float radius, int numSegments) {
    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(centerX, centerY); // Mittelpunkt des Kreises
    for (int i = 0; i <= numSegments; i++) {
        float theta = 2.0f * M_PI * float(i) / float(numSegments);
        float x = radius * cosf(theta);
        float y = radius * sinf(theta);
        glVertex2f(x + centerX, y + centerY);
    }
    glEnd();
}

int main() {

    // Initialisiere GLFW
    if (!glfwInit()) {
        return -1;
    }

    // Erstelle ein Fenster
    GLFWwindow* window = glfwCreateWindow(800, 600, "Kreis", NULL, NULL);

    if (!window) {
        glfwTerminate();
        return -1;
    }

    // Setze den aktuellen Kontext auf das erstellte Fenster
    glfwMakeContextCurrent(window);

    // Haupt-Render-Schleife
    while (!glfwWindowShouldClose(window)) {

        glClear(GL_COLOR_BUFFER_BIT);

        // Zeichne den Kreis
        glColor3f(1.0f, 1.0f, 1.0f); // Farbe (weiß)
        drawCircle(400, 300, 50, 100);

        glfwSwapBuffers(window);
        glfwPollEvents();

    }

    // Beende GLFW
    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;

}
von  

1 Antwort

1 Pluspunkt 0 Minuspunkte

Mit der Funktion

glOrtho(0, 800, 0, 600, -1, 1);

kannst du den Projektor auf orthografisch setzen. Bei der orthographischen Projektion gibt es keine Tiefe. Das ist notwendig um 2D Objekte zu zeichnen.

#include <GLFW/glfw3.h>
#include <math.h>

void drawCircle(float centerX, float centerY, float radius, int numSegments) {
    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(centerX, centerY); // Mittelpunkt des Kreises
    for (int i = 0; i <= numSegments; i++) {
        float theta = 2.0f * M_PI * float(i) / float(numSegments);
        float x = radius * cosf(theta);
        float y = radius * sinf(theta);
        glVertex2f(x + centerX, y + centerY);
    }
    glEnd();
}

int main() {

    // Initialisiere GLFW
    if (!glfwInit()) {
        return -1;
    }

    // Erstelle ein Fenster
    GLFWwindow* window = glfwCreateWindow(800, 600, "Kreis", NULL, NULL);

    if (!window) {
        glfwTerminate();
        return -1;
    }

    // Setze den aktuellen Kontext auf das erstellte Fenster
    glfwMakeContextCurrent(window);
    
    glOrtho(0, 800, 0, 600, -1, 1); // Setze den orthografischen Projektor

    // Haupt-Render-Schleife
    while (!glfwWindowShouldClose(window)) {

        glClear(GL_COLOR_BUFFER_BIT);

        // Zeichne den Kreis
        glColor3f(1.0f, 1.0f, 1.0f); // Farbe (weiß)
        drawCircle(400, 300, 50, 100);

        glfwSwapBuffers(window);
        glfwPollEvents();

    }

    // Beende GLFW
    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;

}
von (716 Punkte)