Here is a code segment in java intended to rotate the vertices with coordinates A(10,10),B(20,10),C(20,20),D(10,20) of a square by an angle about the center point of the square. The side of the square is 10 points. The angle of rotation is 90 degree. Ideally after rotation A must become B, B must become C, C must become D and D becomes A.
private Point getRotation(Point start, int side, int rotation){
int x = start.getX();
int y = start.getY();
int pivot_x = x + (side/2);
int pivot_y = y + (side/2);
float angle = (float)Math.toRadians(rotation);
int xR = (int)(pivot_x + (x -pivot_x)*Math.cos(angle) - (y - pivot_y)*Math.sin(angle));
int yR = (int)(pivot_y + (x -pivot_x)*Math.sin(angle) + (y - pivot_y)*Math.cos(angle));
return new Point(xR,yR);
}
public static void main(String[] args) {
Square s = new Square();
Point rotatedPoint1= s.getRotation(new Point(10,10), 10, 90);
System.out.println("{"+rotatedPoint1.getX()+","+rotatedPoint1.getY()+"}");
Point rotatedPoint2= s.getRotation(new Point(20,10), 10, 90);
System.out.println("{"+rotatedPoint2.getX()+","+rotatedPoint2.getY()+"}");
Point rotatedPoint3= s.getRotation(new Point(20,20), 10, 90);
System.out.println("{"+rotatedPoint3.getX()+","+rotatedPoint3.getY()+"}");
Point rotatedPoint4= s.getRotation(new Point(10,20), 10, 90);
System.out.println("{"+rotatedPoint4.getX()+","+rotatedPoint4.getY()+"}");
}
The result that is achieved are not correct
point A(10,10) rotated to (20,10) ---- correct
point B(20,10) rotated to (30,10) ---- INCORRECT
point C(20,20) rotated to (30,20) ---- INCORRECT
point D(10,20) rotated to (20,20) ---- INCORRECT
The formula applied is
if (h,k) are the points about which the point (x,y) needs to be rotated by an angle THETA, then the Coordinates after rotation (xR, yR) are
- xR = h + (x-h)cos(THETA) - (y-k)sin(THETA)
- yR = k + (x-h)sin(THETA) + (y-k)cos(THETA)
Where is the problem?
side
? The formula you give is for rotating a point about another point by a given angle; but your method takes another parameter ofside
. – chiastic-securityint
coordinates of the points might cause some rouning errors. Consider using aPoint2D.Double
) – Marco13getRotation
method wants to bestatic
. That was a bit confusing. – chiastic-security