Search code examples
javagraphicsawtjava-2drotational-matrices

java skewed shape when rotated


So I have a shape and I want to rotate it with respect to the y-axis. I'm pretty sure my rotation matrix is correct, here's how the rotation matrix looks like in our guide:

enter image description here

And here's the code I implemented:

public static void rotate3Dy(float[] xCoords, float[] yCoords, float[] zCoords, float angle) {
    float cosine_angle = (float) Math.cos(angle);
    float sine_angle = (float) Math.sin(angle);

    for (int i = 0; i < yCoords.length; i++) {
        xCoords[i] = (xCoords[i] * cosine_angle) + (zCoords[i] * sine_angle) + 0;
        zCoords[i] = (-xCoords[i] * sine_angle) + (zCoords[i] * cosine_angle) + 0;
    }
}

Rotating the shape up/down/left/right alone looks fine, but when I rotate it either left or right after being rotated up/down it starts getting skewed.

enter image description here

What am I missing/doing wrong here?


Solution

  • Presumably the skew is caused by the following flaw in your rotation transform: In the loop of your rotate3Dy-method you transform xCoords[i] and then you use the transformed value to transform zCoords[i] instead of computing the latter with the untransformed value of xCoords[i].

    Try the following: Clone the xCoords-array before its transformation i.e. replace

        for (int i = 0; i < yCoords.length; i++) {
            xCoords[i] = (xCoords[i] * cosine_angle) + (zCoords[i] * sine_angle) + 0;
            zCoords[i] = (-xCoords[i] * sine_angle) + (zCoords[i] * cosine_angle) + 0;
        }
    

    with

        float[] xCoordsTmp = xCoords.clone();
        for (int i = 0; i < yCoords.length; i++) {
            xCoords[i] = (xCoordsTmp[i] * cosine_angle) + (zCoords[i] * sine_angle) + 0;
            zCoords[i] = (-xCoordsTmp[i] * sine_angle) + (zCoords[i] * cosine_angle) + 0;
        }
    

    Maybe that fixes the problem.