How to rotate a vertex around a certain point?
The easiest approach is to compose three transformations:
- A translation that brings point 1 to the origin
- Rotation around the origin by the required angle
- A translation that brings point 1 back to its original position
When you work this all out, you end up with the following transformation (where x
is the desired angle of rotation in radians):
newX = centerX + (point2x-centerX)*Math.cos(x) - (point2y-centerY)*Math.sin(x);
newY = centerY + (point2x-centerX)*Math.sin(x) + (point2y-centerY)*Math.cos(x);
Note that this makes the assumption that the angle x
is negative for clockwise rotation (the so-called standard or right-hand orientation for the coordinate system). If that's not the case, then you would need to reverse the sign on the terms involving sin(x)
.
Assuming you are usign the Java Graphics2D API, try this code -
Point2D result = new Point2D.Double();
AffineTransform rotation = new AffineTransform();
double angleInRadians = (angle * Math.PI / 180);
rotation.rotate(angleInRadians, pivot.getX(), pivot.getY());
rotation.transform(point, result);
return result;
where pivot is the point you are rotating around.
You need a 2-d rotation matrix http://en.wikipedia.org/wiki/Rotation_matrix
Your new point will be
newX = centerX + ( cosX * (point2X-centerX) + sinX * (point2Y -centerY))
newY = centerY + ( -sinX * (point2X-centerX) + cosX * (point2Y -centerY))
because you are rotating clockwise rather than anticlockwise
Translate "1" to 0,0
Rotate
x = sin(angle) * r; y = cos(angle) * r;
Translate it back