我根据鼠标位置旋转相机。但我希望仅当鼠标左键或右键按下时才激活此功能。这段代码的问题是我必须松开并再次按下才能让程序注意到我已经移动了鼠标。
当使用键盘按键并移动鼠标时,它起作用了。
尝试 glutPostRedisplay 但我不确定它是否是我需要的或如何使用它。
void processMouse(int button, int state, int x, int y) {
if (state == GLUT_DOWN) {
if (button == GLUT_LEFT_BUTTON) {mouseM=true;} if (button == GLUT_RIGHT_BUTTON) {mouseN=true;}
} if (state == GLUT_UP){ if (button == GLUT_LEFT_BUTTON){mouseM=false;} if (button == GLUT_RIGHT_BUTTON) {mouseN=false;} }
}
void mouseMove(int x, int y){
if (x < 0) angleX = 0.0; else if (x > w) angleX = 180.0; else //angleX = 5.0 * ((float) x)/w; angleX = (x-320)/50; angleZ = angleX; angleY= (y-240)/50;
}
最佳答案
您可以结合glutMouseFunc
、glutMotionFunc
和glutPassiveMotionFunc
来实现它。
(1)glutMotionFunc
仅在按下鼠标按钮时随时告诉您光标的(x, y)
。另一方面,当没有按下任何按钮时,glutPassiveMotionFunc
会告诉您(x, y)
。 (查看 glut specification 了解更多详细信息)。
(2) 组合这些功能
首先,准备 onLeftButton(int x, int y)
和 onRightButton(int x, int y)
来处理左键按下和右键按下事件分别如下:
void onLeftButton(int x, int y){
//change variables for your glRotatef function for example
//(x, y) is the current coordinate and
//(preMouseX, preMouseY) is the previous coordinate of your cursor.
//and axisX is the degree for rotation along x axis. Similar as axisY.
axisX += (y - preMouseY);
axisY += (x - preMouseX);
...
}
void onRightButton(int x, int y){
//do something you want...
}
其次,为glutMouseFunc
准备一个函数,比如onMouse
,例如:
glutMouseFunc(onMouse);
在 onMouse
函数中,它会像这样:
void onMouse(int button, int state, int x, int y)
{
if(state == GLUT_DOWN){
if(button == GLUT_RIGHT_BUTTON)
glutMotionFunc(onRightButton);
else if(button == GLUT_LEFT_BUTTON)
glutMotionFunc(onLeftButton);
}
}
完成这些操作后,只要按住左/右按钮,您就可以随时获取光标的(x, y)
。
有关如何组合这些功能的更多信息,您可以查看 3.030 部分 this site
关于c++ - GLUT 鼠标位置未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4521656/