RayCasting不考虑相机旋转

时间:2019-03-01 14:06:06

标签: java opengl lwjgl raycasting

我正在使用LWJGL和openGL,并且正在尝试实现RayCasting将光标位置转换为3D点。

我尝试了多种方法(内置和完全手动),但结果始终相同: Gif of Problem

gif中的墙是x = 0,y = 0,z = 1平面,我正在使用二进制搜索来找到交点并将立方体移动到光标位置。

以下是一些相关代码:

private static Vector3f mouseRay = new Vector3f();

protected static GLFWCursorPosCallback cursorPosCallback = new GLFWCursorPosCallback() {
        @Override
        public void invoke(long window, double xpos, double ypos) {
            cursorPosX = xpos;
            cursorPosY = ypos;

            Vector3f origin = new Vector3f();
            int[] viewport = new int[4];
            viewport[2] = Game.window.getWidth();
            viewport[3] = Game.window.getHeight();

            MasterRenderer.getProjectionMatrix()
                    .unprojectRay((float) xpos, (float) (Game.window.getHeight() - ypos), viewport, origin, mouseRay);

            mouseRay.normalize();
//wallIntersection = binarySearch(Game.activeCamera.getPosition(), 0, 0, RAYCASTING_RAY_RANGE, mouseRay);

            float distance = Intersectionf.intersectRayPlane(Game.camera.getPosition(), mouseRay, new Vector3f(0,0,0), new Vector3f(0,0,1), 1e-5f);
            wallIntersection = getPointOnRay(Game.camera.getPosition(), mouseRay, distance);

public static Vector3f getPointOnRay(Vector3f origin, Vector3f ray, float distance) {
        Vector3f camPos = origin;
        Vector3f start = new Vector3f(camPos.x, camPos.y, camPos.z);
        Vector3f scaledRay = new Vector3f(ray.x * distance, ray.y * distance, ray.z * distance);
        return start.add(scaledRay);
    }

通过鼠标回调完成射线的更新。我也在回调之外尝试过,但是回调听起来更有效。

以及渲染器的投影矩阵

 private void createProjectionMatrix() {
        float aspectRatio = (float) Game.window.getWidth() / (float) Game.window.getHeight();
        float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio);
        float x_scale = y_scale / aspectRatio;
        float frustum_length = FAR_PLANE - NEAR_PLANE;

        projectionMatrix = new Matrix4f();
        projectionMatrix._m00(x_scale);
        projectionMatrix._m11(y_scale);
        projectionMatrix._m22( -((FAR_PLANE + NEAR_PLANE) / frustum_length) );
        projectionMatrix._m23( -1 );
        projectionMatrix._m32( -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length) );
        projectionMatrix._m33( 0 );
    }

我觉得我需要旋转viewMatrix:

Matrix4f matrix = new Matrix4f()
                .rotateX((float) Math.toRadians(camera.getPitch()))
                .rotateY((float) Math.toRadians(camera.getYaw()))
                .rotateZ((float) Math.toRadians(camera.getRoll()))
                .translate(new Vector3f(-camera.getPosition().x, -camera.getPosition().y, -camera.getPosition().z));

但是我只是无法正常工作。任何帮助将不胜感激!

0 个答案:

没有答案