public class Asteroid extends MovingPolygon { /* This class represents an asteriod. An asteroid travels through space at a certain velocity (speed,direction). To keep asteroids convex when randomly creating them, we create them from circles, positioning subsequent vertices by adding a random angle. Of course, this is perfect for fast "non-collision detection". public variables: center, radius, speed, direction public functions: reshape, translate, move, rotate, inCollision, toPolygon */ public final static int MAX_VERTICES = 8; // maximum number of vertices an asteroid may have // constructors ----------------------------------------------------------------------------- public Asteroid() { this(MAX_VERTICES); } // make a random asteroid using the maximum limit public Asteroid(Asteroid a) { super(a); } // make a copy of an asteroid public Asteroid(int maxVertices) // make a random asteroid with a limited number of vertices { speed = 0.5 + Math.random(); // 0.5 to 1.5 direction = Math.random() * 2.0 * Math.PI; // 0 to 2 PI radius = Math.random() * 10.0 + 6.0; // 6 to 16 double[] angles = generateAngles(maxVertices); reposition(angles, new DPoint(Math.random() * X_LIMIT, Math.random() * Y_LIMIT)); } //------------------------------------------------------------------------------------------- public void reshape(double dr) // change the shape of an asteroid, even the radius length! { radius += dr; double[] angles = generateAngles(MAX_VERTICES); reposition(angles,center); } private double[] generateAngles(int maxVertices) { // generate random angles for an Asteroid with [3..maxVertices] vertices double angle, angleSum = 0.0, vertexConstant = new Integer(maxVertices).doubleValue() - 4.0; double[] angles = new double[maxVertices]; boolean isFullCircle = false; int i; // add random angles to generate subsequent vertices until we go around the circle for (i = 0; i < maxVertices && !isFullCircle; i++) { angle = 2.0 * Math.PI / (Math.random() * vertexConstant + 4.0); if (angleSum + angle >= 2.0 * Math.PI) isFullCircle = true; else { angles[i] = angle; angleSum += angles[i]; } } vertices = new DPoint[isFullCircle ? i-1 : i]; return angles; } // generateAngles() private void reposition(double[] angles, DPoint newCenter) { // reposition the Asteroid with the new center point center = newCenter; double angleSum = direction; for (int i = 0; i < vertices.length; i++) { angleSum -= angles[i]; vertices[i] = new DPoint(center.x + radius * Math.cos(angleSum), center.y + radius * Math.sin(angleSum) ); } } // reposition() }