我想通过鼠标交互在openGL Glut中绘制一个多边形,每次左键单击都将是一个顶点,并且将在每个顶点之间绘制一条线。单击鼠标右键时,多边形将关闭,从最后一个顶点到第一个顶点绘制一条线。我想出了这个,但它似乎不起作用。
void draw_polygon(int button, int state, int x, int y) {
bool right_pushed = 0;
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
p1.x = x;
p1.y = 480 - y;
//if right is clicked draw a line to here
first.x = x;
first.y = 480 - y;
}
while (right_pushed == false) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
p2.x = x;
p2.y = 480 - y;
}
GLfloat dx = p2.x - p1.x;
GLfloat dy = p2.y - p1.y;
GLfloat x1 = p1.x;
GLfloat y1 = p1.y;
GLfloat step = 0;
if (abs(dx) > abs(dy)) {
step = abs(dx);
}
else {
step = abs(dy);
}
GLfloat xInc = dx / step;
GLfloat yInc = dy / step;
for (float i = 1; i <= step; i++) {
glVertex2i(x1, y1);
x1 += xInc;
y1 += yInc;
}
p1.x = p2.x;
p1.y = 480 - y;
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
right_pushed = 1;
p2.x = first.x;
p2.y = first.y;
dx = p2.x - p1.x;
dy = p2.y - p1.y;
x1 = p1.x;
y1 = p1.y;
step = 0;
if (abs(dx) > abs(dy)) {
step = abs(dx);
}
else {
step = abs(dy);
}
xInc = dx / step;
yInc = dy / step;
for (float i = 1; i <= step; i++) {
glVertex2i(x1, y1);
x1 += xInc;
y1 += yInc;
}
}
}
glEnd();
glFlush();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(200, 200);
glutInitWindowSize(640, 480);
glutCreateWindow("windows");
glutDisplayFunc(display);
glutMouseFunc(draw_polygon);//
init();
glutMainLoop();
return 0;
}
我还试图找出如何添加一个功能,当我从菜单中选择时,我可以从创建这个多边形到编辑它,我可以选择一个顶点,移动它,形状会相应地改变。