The Java applet below shows how a square centered at the origin (0,0)
(the blue dot in the middle of the square) can be rotated around the origin by
any angle (positive or negative). The source code is available
here. To use the applet, enter an angle in the
Degrees textfield, then hit the Rotate button (or the Enter key).
Note: Angles must be numbers, no letters are allowed.
What the applet does is rotate each vertex (P1-P4) of the square around the origin by the same angle, then join the vertices by lines. To do this, it uses the formula for the point (x',y') obtained by rotating a point (x,y) around the origin by an angle θ:
(x',y') = (x⋅cos(θ) - y⋅sin(θ), x⋅sin(θ) + y⋅cos(θ))
This formula is a simple result of the addition formulas for sine and cosine (discussed in Section 3.2 in the book).
To prove this formula, let (x,y) be a point a distance r > 0 from the origin, so that x = r⋅cos(α) and y = r⋅sin(α) for some angle α, as in the picture below:
Rotating (x,y) counterclockwise around the origin by an angle θ puts (x,y) in a new location (x',y'), still a distance r from the origin. And as the picture shows, the line segment from the origin to (x',y') makes a total angle of θ+α with the positive x-axis. So we know that
x' = r⋅cos(θ+α)
= r⋅(cos(θ)cos(α) - sin(θ)sin(α))
= (r⋅cos(α))⋅cos(θ) - (r⋅sin(α))⋅sin(θ)
= x⋅cos(θ) - y⋅sin(&theta);
and
y' = r⋅sin(θ+α)
= r⋅(sin(θ)cos(α) + cos(θ)sin(α))
= (r⋅cos(α))⋅sin(θ) + (r⋅sin(α))⋅cos(θ)
= x⋅sin(θ) + y⋅cos(θ)
Of course in Java (and other programming languages and computer software), there are usually built-in functions that can handle the rotation for you (thus hiding the math), which means that you do not have to use the formula directly. This applet is designed (if you read through the source code in rotate2D.java) to unhide that math, just to show how the rotation is done by those built-in functions.