How do I fix my orthographic projection math when it renders cubes behind me on my screen?

28 Views Asked by At

In my math, everything is functional except when I rotate my camera 180 degrees, I can see all the blocks behind me. It appears to invert the controls, yet they are actually functional because it's still drawing the blocks as if they were in the correct position, simply displaying them on the screen. This is the code I used to do the math for orthographic projection.

public double[][] draw() {
        double [][] rotationZ = new double [][]{
            {cos(angleZ), -sin(angleZ), 0},
            {sin(angleZ), cos(angleZ), 0},
            {0, 0, 1},
        };

        double [][] rotationX = new double [][]{
            {1, 0, 0},
            {0, cos(angleX), -sin(angleX)},
            {0, sin(angleX), cos(angleX)},
        };

        double [][] rotationY = new double [][]{
            {cos(angleY), 0, sin(angleY)},
            {0, 1, 0},
            {-sin(angleY), 0, cos(angleY)},
        };

        double[][] projected = new double[8][];
        for(int i = 0; i < points.size(); i ++) {
            double[] rotated = multiplyMatrices(rotationY, points.get(i).toMatrix());
            rotated = multiplyMatrices(rotationX, rotated);
            rotated = multiplyMatrices(rotationZ, rotated);
            double z = 1 / rotated[2];

            double[][] projection = new double[][]{
                    {z, 0, 0},
                    {0, z, 0},
                };

            double[] projected2d = multiplyMatrices(projection, rotated);

            projected2d = scaleMatrix(projected2d, 200);

            projected[i] = projected2d;
        }
        return(projected);
    }

Here's my matrix multiplication code:

private double[][] multiplyMatrices(double A[][], double B[][])
{
    int row1 = A.length;
    int col1 = A[0].length;
    int row2 = B.length;
    int col2 = B[0].length;

    double C[][] = new double[row1][col2];

    for (int i = 0; i < row1; i++) {
        for (int j = 0; j < col2; j++) {
            for (int k = 0; k < row2; k++)
                C[i][j] += A[i][k] * B[k][j];
        }
    }

    return(C);
}

private double[] multiplyMatrices(double A[][], double B[])
{
    int colsA = A[0].length;
    int rowsA = A.length;
    int rowsB = B.length;

    double[] result = new double[rowsA];
    for (int j = 0; j < rowsA; j ++) {
            double sum = 0;
            for (int n = 0; n < colsA; n ++) {
                sum += A[j][n] * B[n];
            }
            result[j] = sum;
        }
    return result;
}

I tried making it so the x, y, and z positions added to the cubes were absolute values in case that was messing anything up, but it did not change anything because I realized that it was all in the rotation, and if I set the cube rotation to 180 degrees, it acted normally but displayed on the screen and acted inverted.

0

There are 0 best solutions below