forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotatingPolygon.java
More file actions
75 lines (62 loc) · 1.82 KB
/
RotatingPolygon.java
File metadata and controls
75 lines (62 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.Arrays;
/**
* A polygon that rotates around its center.
*/
public class RotatingPolygon extends RegularPolygon {
private int xmid;
private int ymid;
private int angle; // in degrees
private int[] x0; // original xpoints
private int[] y0; // original ypoints
/**
* Constructs a rotating polygon.
*
* @param nsides the number of sides
* @param radius from center to vertex
*/
public RotatingPolygon(int nsides, int radius) {
super(nsides, radius);
center();
}
/**
* Sets the rotation point to the middle.
*/
public void center() {
// find the average x and y values
int xsum = 0;
int ysum = 0;
for (int x : xpoints) {
xsum += x;
}
for (int y : ypoints) {
ysum += y;
}
xmid = (int) Math.round(xsum / npoints);
ymid = (int) Math.round(ysum / npoints);
// reset the rotation direction
angle = 359;
// save the original x and y points
x0 = Arrays.copyOf(xpoints, npoints);
y0 = Arrays.copyOf(ypoints, npoints);
}
@Override
public void step() {
// update the rotation angle
angle = (angle + 1) % 360;
final double RAD = Math.toRadians(angle);
final double COS = Math.cos(RAD);
final double SIN = Math.sin(RAD);
// translate the polygon points
for (int i = 0; i < npoints; i++) {
double t = x0[i] - xmid;
double v = y0[i] - ymid;
xpoints[i] = (int) Math.round(xmid + t * COS - v * SIN);
ypoints[i] = (int) Math.round(ymid + t * SIN + v * COS);
}
}
@Override
public void translate(int deltaX, int deltaY) {
super.translate(deltaX, deltaY);
center();
}
}