import objectdraw.*; import java.util.Random; // Animated ball for the breakout game public class BreakoutBall extends ActiveObject { // Ball's initial speed private final static double INIT_Y = 100; private static final double XSPEED_SCALER = 3; // Size of ball private static final double BALLSIZE = 10; // delay between moves private static final double DELAY = 30; // the ball itself private FilledOval theBall; // the bricks ball might bounce off private BreakoutBricks bricks; // the boundary within which the ball should stay private DrawingCanvas canvas; // the paddle trying to hit the ball private FilledRect paddle; // current ball speed private double xSpeed; private double ySpeed = -INIT_Y; // create a new ball. remember all the things it might hit public BreakoutBall(BreakoutBricks theBricks, FilledRect thePaddle, DrawingCanvas theCanvas) { // set a random X speed (positive or negative) Random rand = new Random(); xSpeed = (rand.nextDouble() - 0.5) * XSPEED_SCALER * INIT_Y; // draw the ball theBall = new FilledOval(thePaddle.getX() + thePaddle.getWidth()/2, thePaddle.getY() - 2 * BALLSIZE, BALLSIZE, BALLSIZE, theCanvas); // remember the obstacles bricks = theBricks; paddle = thePaddle; canvas = theCanvas; start(); } // bounce the ball around the playing area public void run() { double lastTime = System.currentTimeMillis(); while (theBall.getY() < canvas.getHeight()) { pause(DELAY); double elapsedTime = System.currentTimeMillis() - lastTime; lastTime = lastTime + elapsedTime; theBall.move(elapsedTime * xSpeed / 1000, elapsedTime * ySpeed / 1000); // see if you need to bounce off one of the boundary's sides if (theBall.getX() < 0) { // bounce off left side xSpeed = -xSpeed; } else if (theBall.getX() + BALLSIZE > canvas.getWidth()) { // bounce off right side xSpeed = -xSpeed; } // see if you hit the top of the boundary if (theBall.getY() < 0) { ySpeed = -ySpeed; } // see if you hit a brick FilledRect hitBrick = bricks.getIntersectedBrick(theBall); if (hitBrick != null) { bounceOffRect(hitBrick); } // check the paddle if (theBall.overlaps(paddle)) { bounceOffRect(paddle); } } } // A crude approximation of the phsyical process // of a ball bouncing off a brick (or the paddle). private void bounceOffRect(FilledRect box) { double centerX = theBall.getX() + BALLSIZE/2; if (centerX > box.getX() && centerX < box.getX() + box.getWidth()) { // hit the top of the rectangle ySpeed = -ySpeed; } else { // hit the side of the rectangle xSpeed = -xSpeed; } } }