Ben Tanos Ben Tanos - 29 days ago 13
C++ Question

OpenGL - Draw a Triangle wherever I click?

I have an OpenGL project with a screen size of 1000x800, and I want to be able to draw a triangle when I click the left mouse button.

I already have a mouse function set up that works fine:

struct point
{
int x;
int y;
};

std::vector <point> dots;
point OneDot;

void processMouse(int button, int state, int x, int y)
{

if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
{
int yy;
yy = glutGet(GLUT_WINDOW_HEIGHT);
y = yy - y; /* In Glut, Y coordinate increases from top to bottom */
OneDot.x = x;
OneDot.y = y;

dots.push_back(OneDot);
}
}

void display(){
for (int i = 0; i < dots.size();i++){
glPointSize(10)
glBegin(GL_POINTS);
glVertex2i(dots[i].x, dots[i].y);
}
}


So in my
display()
function, how can I add some code that prints a triangle at the mouse location when I click?

Answer

In your code you're almost there. Two things you have to add: In your mouse event handler you have to set the flag that tells your window manager (in your case GLUT) to refresh the display. That function would be glutPostRedisplay.

Then in your display function you have to push 3 vertices instead of 1 and change the primitive type to GL_TRIANGLES. Like this

void processMouse(int button, int state, int x, int y)
{

    if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
    {
        int yy;
        yy = glutGet(GLUT_WINDOW_HEIGHT);
        y = yy - y; /* In Glut, Y coordinate increases from top to bottom */
        OneDot.x = x;
        OneDot.y = y;

        dots.push_back(OneDot);
        glutPostRedisplay(); ///<<<<<<<<<<
   }
}

and

void display(){
    glBegin(GL_TRIANGLES);
    for (int i = 0; i < dots.size();i++){
        glPointSize(10)

        glVertex2i(dots[i].x-3, dots[i].y-5);
        glVertex2i(dots[i].x+3, dots[i].y-5);
        glVertex2i(dots[i].x, dots[i].y+5);
    }
    glEnd();
}

or, if you want to define the corners of the triangle(s) by the clicks just

void display(){
    glBegin(GL_TRIANGLES);
    for (int i = 0; i < dots.size();i++){
        glPointSize(10);

        glVertex2i(dots[i].x, dots[i].y);
    }
    glEnd();
}

You don't really have to check if 3 <= dots.size() because OpenGL will simply draw nothing then.

Comments