夥計們,我在使用過量鼠標功能的程序中遇到了一個問題。我正在做一個矩形繪製在屏幕上,並在鼠標功能我將像素座標轉換爲世界座標與寬度600和高度500我想要什麼時用戶點擊給定的矩形顏色將是紅色的,但我如何執行此任務如何確定鼠標點擊這些矩形。
代碼:Opengl鼠標點擊矩形
#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
@segevara是正好當它點擊它改變顏色 – hamel123