Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openGL(c) draw square

Tags:

c

opengl

i need to draw a square using c (openGL), i only have 1 coordinate which is the center of the square (lets say 0.5,0.5) and i need to draw a square ABCD with each side 0.2 length (AB,BC,CD,DA), I tried using the next function but it does not draw anything for some reson,

void drawSquare(double x1,double y1,double radius)
{
    glColor3d(0,0,0);
    glBegin(GL_POLYGON);

    double locationX = x1;
    double locationY = x2;
    double r = radius;

    for(double i=0; i <= 360 ; i+=0.1)
    {
        glVertex2d(locationX + radius*i, locationY + radius*i);
    }

    glEnd();
}

can someone please tell me why its not working\point me to the right direction (i do not want to draw polygon with 4 coordinated normally, but with only 1 coordinate with a givven radius, thanks!

like image 939
Coder123 Avatar asked Dec 17 '25 22:12

Coder123


2 Answers

Your code will not even draw a circle. If anything, it will draw a diagonal line extending out of the view area very quickly. A circle plot would need to use sine and cosine, based on the radius and angle.

I have not tried this code, but it needs to be more like this to draw a square.

void drawSquare(double x1, double y1, double sidelength)
{
    double halfside = sidelength / 2;

    glColor3d(0,0,0);
    glBegin(GL_POLYGON);

    glVertex2d(x1 + halfside, y1 + halfside);
    glVertex2d(x1 + halfside, y1 - halfside);
    glVertex2d(x1 - halfside, y1 - halfside);
    glVertex2d(x1 - halfside, y1 + halfside);

    glEnd();
}

There are no normals defined: perhaps I should have travelled counter-clockwise.

like image 114
Weather Vane Avatar answered Dec 20 '25 12:12

Weather Vane


Simple way to draw a square is to use GL_QUADS and the four vertices for the four corners of the square. Sample code is below-

glBegin(GL_QUADS);
glVertex2f(-1.0f, 1.0f); // top left
glVertex2f(1.0f, 1.0f); // top right 
glVertex2f(1.0f, -1.0f); // bottom right
glVertex2f(-1.0f, -1.0f); // bottom left
glEnd();

Since in the case you have to draw square from the mid point which is interaction of two diagonals of square. You use the following facts and draw the same.

  • length of diagonal = x*square root of 2 (x=side of square)
  • diagonals of a square are perpendicular
  • diagonals of a square are the same length

If your point is at 0.5,0.5 which coordinate of interaction point, and side is 0.2. So you can easily determine the point coordinate of four corners as in the figure given below and code it accordingly.

enter image description here

like image 44
OpenGL Projects Avatar answered Dec 20 '25 12:12

OpenGL Projects



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!