M.Walker
M.Walker

Reputation: 33

I have to create a two methods one for a clockwise rotation and the other anticlockwise

I have two methods one to take points that the user enters then perform a calculation to rotate is 90 degrees clockwise while in the other method, its the exact same only 90 degrees anticlockwise. I have tried it but i`m getting the wrong results, any suggestion on ways to fix it,

private static String Clockwise(int Amount, int[] x, int[] y) {
        String message = "";
        int[] tempX = x;
        int[] tempY = y;

        for (int count = 0; count <= Amount; count++) {//amount of times
            message = "\n";
            for (int index = 0; index < pointer; index++) {//go through array
                tempX[index] = tempX[index] * -1;//multiply X
                tempY[index] = tempY[index] * 1;//multiply Y

                message += ("(" + y[index] + "," + x[index] + ")\n");//output
            }//end for  
        }//end outerfor
        return message;
    }//end clockwise

    private static String AntiClockwise(int Amount, int[] x, int[] y) {
        String message = "";
        int[] tempX = x;
        int[] tempY = y;
        for (int count = 0; count <= Amount; count++) {//amount of times
            message = "\n";
            for (int index = 0; index < pointer; index++) {//go through for loop
                tempX[index] = tempX[index] * 1;//multiply X
                tempY[index] = tempY[index] * -1;//multiply Y
                message += ("(" + tempY[index] + "," + tempX[index] + ")\n");//create message
            }//end for  
        }//end outerfor

        return message;
    }//end anticlockwise

Upvotes: 0

Views: 232

Answers (1)

Andy Turner
Andy Turner

Reputation: 140328

To rotate anti-clockwise by a general angle around the origin, the formula is:

x_new =  cos(theta)*x - sin(theta)*y
y_new =  sin(theta)*x + cos(theta)*y

So, if you want to rotate by some multiple of 90 degrees, you can simply use:

double theta = Math.toRadians(90 * N);

and substitute that into the formula. This means that you don't need a loop to rotate N times - just rotate once by the actual angle.


However, if you want to do it by 90 degrees on each rotation, you can simply substitute in the values of cos(90 deg) and sin(90 deg) (to do an anticlockwise rotation):

x_new = cos(90 deg)*x - sin(90 deg)*y = 0*x - 1*y = -y
y_new = sin(90 deg)*x + cos(90 deg)*y = 1*x + 0*y =  x

Hence:

x_new = -y
y_new = x

There is advantage in doing it this way, since a couple of assignments like this are a lot faster than doing the full math.

Note that you have to be careful not to write:

x = -y;
y = x;

because the second of these statements uses the result of the first. You need to store the original x in a temporary variable to do this correctly.

Upvotes: 2

Related Questions