OpenGL - 用鼠标移动相机 [英] OpenGL - moving camera with mouse

查看:48
本文介绍了OpenGL - 用鼠标移动相机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何解释这一点,但希望你能理解我的意思.

I'm not sure exactly how to explain this but hopefully you'll understand what I mean.

基本上我画了一个立方体,想拖动鼠标来查看所有的边.仅水平或垂直旋转很好,但如果我尝试将这些组合起来,事情就会变得有点奇怪.

Basically I've drawn a cube and want to drag the mouse around to view all the sides. Rotating only horizontally or vertically is fine, but if I try to combine these then things go a little weird.

例如如果我垂直旋转 180 度(以获得倒置"),然后水平拖动鼠标,则立方体会以与鼠标运动相反的方向旋转.

e.g. if I rotate 180 degrees vertically (to get 'upside down') and then drag the mouse horizontally then the cube spins in the opposite direction to the mouse motion.

这是相关代码:

double camera_angle_h = 0;
double camera_angle_v = 0;

int drag_x_origin;
int drag_y_origin;
int dragging = 0;

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    gluLookAt(0.0, 0.0, 25.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    glRotated(camera_angle_v, 1.0, 0.0, 0.0);
    glRotated(camera_angle_h, 0.0, 1.0, 0.0);

    draw_cube();

    glFlush();
    glutSwapBuffers();
}

void mouse_click(int button, int state, int x, int y) {
    if(button == GLUT_LEFT_BUTTON) {
        if(state == GLUT_DOWN) {
            dragging = 1;
            drag_x_origin = x;
            drag_y_origin = y;
        }
        else
            dragging = 0;
    }
}

void mouse_move(int x, int y) {
    if(dragging) {
        camera_angle_v += (y - drag_y_origin)*0.3;
        camera_angle_h += (x - drag_x_origin)*0.3;
        drag_x_origin = x;
        drag_y_origin = y;
    }
}

推荐答案

正如其他人所说,使用四元数是解决方案.Ken Shoemake 提供了极好的代码,用于在图形宝石 IV 中在四元数和欧拉角之间进行转换(参见 code此处的示例,请参阅欧拉角转换").它还具有与旋转矩阵之间的转换.

As others have said, using quaternions is the solution. Ken Shoemake provides excellent code for converting between quaternions and Euler angles in graphics gems IV (see code samples here, see "Euler Angle Conversion"). It also has conversions to and from rotation matrices.

如果您想使用鼠标进行旋转,可以说黄金标准"是由 Shoemake 在 Graphics Gems IV 中描述的Arcball"界面(可用 现在.Arcball 的改进版本作为轨迹球"随 Glut 库一起分发,当在旋转球体外发生点击时,它提供更直观的界面.它由 Gavin Bell 编写,可在此处获得和这里.Bell 的轨迹球是 Blender 项目 使用的方法,我假设商业包使用类似的东西.

If you want to do rotation using the mouse, arguably the "gold standard" is the "Arcball" interface described by Shoemake in Graphics Gems IV (avalable here, for now). An improved version of Arcball is distributed with the Glut library as "trackball," which offers a more intuitive interface when clicks occur outside the rotation sphere. It was written by Gavin Bell, and is available here and here. Bell's trackball is the approach used by the Blender project, and I presume the commercial packages use something similar.

这篇关于OpenGL - 用鼠标移动相机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆