在3D场景中平移相机

时间:2020-10-29 22:49:38

标签: java opengl 3d camera panning

我正在编写一个3D应用程序,我需要使用鼠标光标来平移相机。与许多3D应用程序一样,您可以按鼠标滚轮并移动鼠标以平移相机。

我正在做的事情是计算鼠标位置的变化( dx dy ),以确定相机应该摇摄多少。要确定相机应朝哪个方向移动,以从相机的角度通过鼠标位置投射光线以获取方向矢量。接下来,我将使用叉积计算鼠标射线的垂直向量,以确定相机应该在哪个轴上移动,并根据 dx dy 进行相应移动。

问题:

当我看着0、0,-1方向(进入屏幕)时,我可以沿X和Y轴正确移动相机。

当我看向0,-1、0方向(进入“地面”)时,我可以沿X轴正确移动相机,但会绕Y轴抖动。抖动会正确地移动到某个点,然后放慢速度甚至朝相反的方向移动。

另一个问题是,由于我只有2D鼠标位置 dx dy ,该如何在Z轴上移动相机?

以下是Im正在使用的代码。也许我的逻辑是错误的,或者我正在监督某些事情。我对向量和矩阵不太熟悉,在学习的同时也对我如此裸露!

    //Calculate the change in mouse position
    float dx = (e.getX() - mouseX) * 0.02f;
    float dy = (e.getY() - mouseY) * 0.02f;

    //project the 2D mouse position to the 3D world position (mouse picking, raycasting) and normalise the vector to get a directional vector
    Vector3f direction = Maths.getRay(e.getX(), e.getY(), this).normalise();

    //Calculate the vector perpendicular to the mouse ray and the "up" vector
    Vector3f perpendicular = Vector3f.cross(direction, new Vector3f(0, 1, 0).normalise(); 

    //Move the camera along the axis
    Vector3f cameraPos = camera.getPosition();
    camera.setPosition(new Vector3f(cameraPos.x + (perpendicular.x * dx) , cameraPos.y + (perpendicular.z * dy), 0));

     //Cache the mouse position for the next iteration
     mouseX = e.getX();
     mouseY = e.getY();

0 个答案:

没有答案
相关问题