【问题标题】:using gluLookAt and mouse to channge viewing angle in opengl/glut在 opengl/glut 中使用 gluLookAt 和鼠标改变视角
【发布时间】:2020-12-15 03:41:40
【问题描述】:

您好,所以我正在尝试使用鼠标功能将 gluLookAt 的视角移动到没有运气到目前为止我试图根据鼠标位置调整 upX 和 upY 但是我希望程序能够完成整个根据鼠标移动围绕对象进行 360 度旋转,并希望它在窗口中的鼠标移动停止时停止。任何帮助将不胜感激我仍在学习

#include <iostream>
#include <math.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

float posX=4, posY=6, posZ=5, targetX=0, targetY=0, targetZ=0, upX=0, upY=1, upZ=0;

void display() {
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0, 4.0/3.0, 1, 40);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, upX, upY, upZ);  

    glColor3f(1.0, 1.0, 1.0);
    glutWireTeapot(1.5);

    glBegin(GL_LINES);
      glColor3f(1, 0, 0); glVertex3f(0, 0, 0); glVertex3f(10, 0, 0);
      glColor3f(0, 1, 0); glVertex3f(0, 0, 0); glVertex3f(0, 10, 0);
      glColor3f(0, 0, 1); glVertex3f(0, 0, 0); glVertex3f(0, 0, 10);
    glEnd();

    glFlush();
}

void usage(){
    std::cout<< "\n\n\
          q,Q: Quit\n\n" ;
          std::cout.flush();
}

void onMouseMove(int x, int y)
{
    posX = x*cos(posY) + PosY*sin(PosX)*sin(yRot) - dz*cos(xRot)*sin(yRot) 
    glutPostRedisplay();
}

void KeyboardFunc (unsigned char key, int eyeX, int eyeY)
{
    switch (key)
    {
       case 'q':
       case 'Q':
           exit(0);
           break;
    }
    glutPostRedisplay();
}

void init() 
{
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3f(1.0, 1.0, 1.0);
    usage();
}

int main(int argc, char** argv) 
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(300,250);
    glutInitWindowSize(800, 600);
    glutCreateWindow("Final");
    init();
    glutDisplayFunc(display);
    glutPassiveMotionFunc(&onMouseMove);
    glutKeyboardFunc(&KeyboardFunc); 
    glutMainLoop();
}

【问题讨论】:

  • 请忽略当前 onMouseMove 代码正在尝试随机操作
  • 您想使用lookAt 在场景中移动以始终将场景保持在中心还是旋转相机?想要使用什么坐标变换将鼠标移动映射到球体?
  • 我不确定我想使用什么坐标变换是什么意思,但形状是茶壶,我希望能够根据鼠标移动将相机围绕茶壶移动 360 度在窗口中
  • 其实你应该使用模型矩阵来做这个工作,根据鼠标移动来改变旋转角度。我认为这是最好的应用程序。
  • 通常一个将滚动设置为零,这个答案是个好建议。

标签: c++ opengl glut


【解决方案1】:

如果你想实现一个轨迹球相机,并且你想用固定功能的管道矩阵堆栈来实现它,实际上不使用gluLookAt() 而使用glRotate/glTranslate 会更简单,如下所示:

glTranslatef(0f, 0f, -radius);
glRotatef(angX, 1f, 0f, 0f);
glRotatef(angY, 0f, 1f, 0f);
glTranslatef(-targetX, -targetY, -targetZ);

其中radius 是“相机”到观察点的距离,angX 是围绕 X 轴的角度,angY 围绕 Y 轴的角度,(targetX, targetY, targetZ) 是观察到的位置点(你的targetX/Y/Z)。

您不必自己计算sin/cos(它由glRotatef 计算),您只需在运动函数中设置/增加angXangY

【讨论】:

  • 这是否会进入 onMouseMove 函数,以便在鼠标移动时使用它,或者将其放置在代码中的其他位置?顺便谢谢你的建议!
  • 它将出现在您需要转换顶部模型视图矩阵的任何位置,例如您当前对gluLookAt() 的调用(因此,而不是gluLookAt())。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多