Coder123
Coder123

Reputation: 854

openGL(c) draw square

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!

Upvotes: 2

Views: 34224

Answers (2)

OpenGL Projects
OpenGL Projects

Reputation: 48

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

Upvotes: 3

Weather Vane
Weather Vane

Reputation: 34585

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.

Upvotes: 8

Related Questions