[译]GLUT教程 - 移动镜头3

Lighthouse3d.com >> GLUT Tutorial >> Input >> Moving the Camera III

 

 

上一节的示例中我们用键盘更改镜头的方向.这一节我们用鼠标来代替.

当用户按下鼠标左键时我们会记录鼠标的X轴位置.当鼠标移动时我们会检测新的X轴位置,并利用位移差距设置一个deltaAngle变量.该变量会加到初始角度以计算镜头当前的方向.

鼠标点击时的X轴位置也需要变量来保存.

float deltaAngle = 0.0f;

int xOrigin = -1;

 

注意xOrigin变量应初始化为一个鼠标输入时永远不会产生的值(至少必须为0).这样可以让我们区分开用户输入的是左键还是其它键.

下面这函数是用来响应处理按键状态的变更:

void mouseButton(int button, int state, int x, int y) {



    // only start motion if the left button is pressed

    if (button == GLUT_LEFT_BUTTON) {



        // when the button is released

        if (state == GLUT_UP) {

            angle += deltaAngle;

            xOrigin = -1;

        }

        else  {// state = GLUT_DOWN

            xOrigin = x;

        }

    }

}

留意到xOrigin变量会在左键松开的时候设置为-1.

 

处理鼠标移动事件的函数实现如下:

void mouseMove(int x, int y) {



    // this will only be true when the left button is down

    if (xOrigin >= 0) {



        // update deltaAngle

        deltaAngle = (x - xOrigin) * 0.001f;



        // update camera's direction

        lx = sin(angle + deltaAngle);

        lz = -cos(angle + deltaAngle);

    }

}

 

在main函数中我们要注册两个新的回调函数:

int main(int argc, char **argv) {



    // init GLUT and create window

    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

    glutInitWindowPosition(100,100);

    glutInitWindowSize(320,320);

    glutCreateWindow("Lighthouse3D - GLUT Tutorial");



    // register callbacks

    glutDisplayFunc(renderScene);

    glutReshapeFunc(changeSize);

    glutIdleFunc(renderScene);



    glutIgnoreKeyRepeat(1);

    glutKeyboardFunc(processNormalKeys);

    glutSpecialFunc(pressKey);

    glutSpecialUpFunc(releaseKey);



    // here are the two new functions

    glutMouseFunc(mouseButton);

    glutMotionFunc(mouseMove);



    // OpenGL init

    glEnable(GL_DEPTH_TEST);



    // enter GLUT event processing cycle

    glutMainLoop();



    return 1;

}

 

完整代码会在下一节给出.

 

你可能感兴趣的:(教程)