Home > Blockchain >  Not able to draw a rectangle in openGl
Not able to draw a rectangle in openGl

Time:05-22

I am new to OpenGl . I am trying to draw a sqaure . I have given the co ordinates rightly.But I am not getting a sqaure but a 5 sided polygon as shown in this figure. enter image description here I have given the following vertices

glVertex2f(-249, -249);
glVertex2f(-249,-209);
glVertex2f(-209,-249);
glVertex2f(-209, -209);

Here is My code:-

#include<GL/glut.h>
#include<stdio.h>

int x, y;
int rFlag = 0;

void draw_pixel(float x1, float y1)
{
    glColor3f(0.0, 0.0, 1.0);
    glPointSize(5.0);
    glBegin(GL_POINTS);
    glVertex2f(x1, y1);
    glEnd();
}

void triangle()
{
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_POLYGON);
    glVertex2f(-249, -249);
    glVertex2f(-249,-209);
    glVertex2f(-209,-249);
    glVertex2f(-209, -209);
    glEnd();
}

float th = 0.0;
float trX = 0.0, trY = 0.0;

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    if (rFlag == 1) //Rotate Around origin
    {
        trX = 0.0;
        trY = 0.0;
        th  = 0.1;
        draw_pixel(0.0, 0.0);

    }

    if (rFlag == 2) //Rotate Around Fixed Point
    {
        trX = x;
        trY = y;
        th  = 0.1;
        draw_pixel(x, y);
    }
    triangle();
    glutPostRedisplay();
    glutSwapBuffers();
}

void myInit()
{
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-500.0, 500.0, -500.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
}

void rotateMenu(int option)
{
    if (option == 1)
        rFlag = 1;
    if (option == 2)
        rFlag = 2;
    if (option == 3)
        rFlag = 3;
}

int main(int argc, char** argv)
{
    printf("Enter Fixed Points (x,y) for Rotation:\n");
    scanf_s("%d %d", &x, &y);
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Create and Rotate Triangle");
    myInit();
    glutDisplayFunc(display);
    glutCreateMenu(rotateMenu);
    glutAddMenuEntry("Rotate around ORIGIN", 1);
    glutAddMenuEntry("Rotate around FIXED POINT", 2);
    glutAddMenuEntry("Stop Rotation", 3);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
    glutMainLoop();
} 

CodePudding user response:

The order of the vertices is wrong. Change the order and draw the vertices either clockwise or counter clockwise:

glBegin(GL_POLYGON);
glVertex2f(-249, -249);
glVertex2f(-209, -249)
glVertex2f(-209, -209);
glVertex2f(-249, -209);
glEnd();
  • Related