【发布时间】:2016-02-11 09:18:43
【问题描述】:
伙计们,我在使用 glut 鼠标功能时遇到了这个程序的问题。我在做什么 在屏幕上绘制一个矩形,在鼠标功能中,我将像素坐标转换为宽度为 600 和高度为 500 的世界坐标如何确定鼠标点击这些矩形。
代码:
#include <cstdlib>
#include<GL\freeglut.h>
#include <iostream>
using namespace std;
float xWorldCoordinate = 0.0f;
float yWorldCoordinate = 0.0f;
float r = 0.0f;
float g = 0.0f;
float b = 0.0f;
float r1 = 0.0f;
float g1 = 0.0f;
float b1 = 0.0f;
bool isRed = false;
void init(void) {
glClearColor(31.0f / 255, 28.0f / 255, 44.0f / 255, 0.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
void MouseButton(int button, int action, int xPixel, int yPixel) {
if (button == GLUT_LEFT_BUTTON && action == GLUT_DOWN) {
yPixel = 500 - yPixel;
xWorldCoordinate = (xPixel / 600.0f) * 2;
yWorldCoordinate = (yPixel / 400.0f) * 2;
xWorldCoordinate = -1 + xWorldCoordinate;
yWorldCoordinate = -1 + yWorldCoordinate;
int index1 = 0;
int index2 = 0;
//Index1
glReadPixels(xPixel, yPixel, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index1);// Read pixel under mouse's cursor and read information from stencil buffer to index when it rectangle index should be equal to 1
if (index1 == 1) {
isRed = !isRed;
if (isRed) {
r = 0.0f;
}
else {
r = 1.0f;
}
//Index 2
// glReadPixels(xPixel, yPixel, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index2);
}
}
glutPostRedisplay();
}
void Rectangles(void) {
glStencilFunc(GL_ALWAYS, 1, -1); //set front and back function and reference value for stencil testing
glBegin(GL_POLYGON);
glColor3f(r, g, b);
glVertex2f(-0.1f, 0.1f);
glVertex2f(-0.1f, -0.1f);
glVertex2f(0.1f, -0.1f);
glVertex2f(0.1f, 0.1f);
glEnd();
//2nd Rectangle
glStencilFunc(GL_ALWAYS, 2, -1);
glBegin(GL_POLYGON);
glColor3f(r1, g1, b1);
glVertex2f(0.66f, 0.84f);
glVertex2f(0.87f, 0.84f);
glVertex2f(0.87f, 0.66f);
glVertex2f(0.66f, 0.66f);
glEnd();
}
void Display(void) {
glClearStencil(0); // specifies the index used by glClear to clear the stencil buffer
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glEnable(GL_STENCIL_TEST);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
Rectangles();
glFlush();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_STENCIL); //Bit mask to select a window with a stencil buffer.
glutInitWindowSize(600, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Mouse");
init();
glutDisplayFunc(&Display);
glutMouseFunc(&MouseButton);
glutMainLoop();
return EXIT_SUCCESS;
}
【问题讨论】:
-
您试图确定单击时是否单击了矩形,我说得对吗?
-
@segevara 是的,正是点击它改变颜色