3d cube y axis rotation not working properly

62 views Asked by At

I am currently creating a rubiks cube project. The cube solves, but now I'm trying to implement a 3d model of this cube.

At the moment the x axis and z axis rotations work correctly, but the y axis rotation seems to start of as a cube but as it rotates round becomes more of a trapezium as it rotates 180'.

I have this code:

Point3D final;
            double x = rotation.x;

            final.x = original.x;
            final.y = original.y * Math.Cos(x) - original.z * Math.Sin(x);
            final.z = original.y * Math.Sin(x) + original.z * Math.Cos(x);
            

            original.x = final.x;
            original.y = final.y;
            original.z = final.z;

            x = rotation.y;

            final.x = original.z * Math.Sin(x) + original.x * Math.Cos(x);
            final.y = original.y;
            final.z = original.y * Math.Cos(x) - original.x * Math.Sin(x);

            original.x = final.x;
            original.y = final.y;
            original.z = final.z;

            x = rotation.z;

            final.x = original.x * Math.Cos(x) - original.y * Math.Sin(x);
            final.y = original.x * Math.Sin(x) + original.y * Math.Cos(x);
            final.z = original.z;
1

There are 1 answers

0
JAlex On

typo. Change line for y-rotation to

final.z = original.z * Math.Cos(x) - original.x * Math.Sin(x);

You were using original.y instead of original.z, but for a y-rotation the value of y does not play into the rotation.


May I suggest you define the rotations in methods

public static class Rotations
{
    public static Point3D RotateAboutX(this Point3D point, double angle)
    {
        return new Point3D(
            point.X,
             Math.Cos(angle) * point.Y- Math.Sin(angle) * point.Z,
             Math.Sin(angle) * point.Y+ Math.Cos(angle) * point.Z);
    }
    public static Point3D RotateAboutY(this Point3D point, double angle)
    {
        return new Point3D(
            Math.Cos(angle) * point.X + Math.Sin(angle) * point.Z,
            point.Y,
            -Math.Sin(angle) * point.X + Math.Cos(angle) * point.Z);
    }
    public static Point3D RotateAboutZ(this Point3D point, double angle)
    {
        return new Point3D(
             Math.Cos(angle) * point.X - Math.Sin(angle) * point.Y,
             Math.Sin(angle) * point.X + Math.Cos(angle) * point.Y,
            point.Z);
    }
}

and then used them as needed. For Example

Point3D final = original.RotateAboutX(rotation.x)
                .RotateAboutY(rotation.y)
                .RotateAboutZ(rotation.z);

or the remain true to the original code

Point3D final = original.RotateAboutX(rotation.x);
original = final;
final = original.RotateAboutY(rotation.y);
original = final;
final = original.RotateAboutZ(rotation.z);