我根据鼠标位置旋转相机。但我希望仅当鼠标左键或右键按下时才激活此功能。这段代码的问题是我必须释放并再次按下才能让程序注意到我已经移动了鼠标。
当使用键盘按键并移动鼠标时,它起作用了。
尝试 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;
}
Run Code Online (Sandbox Code Playgroud)
你可以结合glutMouseFunc,glutMotionFunc和glutPassiveMotionFunc来实现它。
(1)仅当按下鼠标按钮时才随时glutMotionFunc告诉您光标。(x, y)另一方面,当没有按下任何按钮时,glutPassiveMotionFunc会告诉您。(x, y)(查看过剩规范以了解更多详细信息)。
(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...
}
Run Code Online (Sandbox Code Playgroud)
其次,为 准备一个函数glutMouseFunc,onMouse例如:
glutMouseFunc(onMouse);
Run Code Online (Sandbox Code Playgroud)
在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);
}
}
Run Code Online (Sandbox Code Playgroud)
完成这些操作后,(x, y)只有按住左/右按钮,您才能随时离开光标。
有关如何组合这些功能的更多信息,您可以查看本站的 3.030 部分