/* * BallApplet.java * Created on Feb 13, 2005 */ package ball; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; /** * Bouncing ball applet. */ public final class BallApplet extends Applet implements ActionListener { private static final int RADIUS = 10; // pixels private static final int INITIAL_X_VEL = 60; // pixels / second private static final int INITIAL_Y_VEL = 0; // pixels / second private static final int DELAY_MS = 50; // milliseconds private static final double DELAY_S = DELAY_MS / 1000.0; // seconds private static final double GRAVITY = 50; // pixels / second^2 private static final double BOUNCE_RATIO = 0.8; private int height, width; private double xPos, yPos; private double xVel, yVel; public void init() { height = getHeight(); width = getWidth(); xPos = RADIUS; yPos = RADIUS; xVel = INITIAL_X_VEL; yVel = INITIAL_Y_VEL; } public void start() { new Timer(DELAY_MS, this).start(); } public void paint(Graphics g) { g.setColor(Color.BLUE); g.fillOval((int)Math.round(xPos), (int)Math.round(yPos), RADIUS, RADIUS); // find time till bounce in x direction double timeToBounceX = Double.MAX_VALUE; if (xVel > 0) { timeToBounceX = (width - xPos - RADIUS) / xVel; } else if (xVel < 0) { timeToBounceX = (xPos - RADIUS) / -xVel; } // update x position and velocity if(timeToBounceX > DELAY_S) { xPos += DELAY_S * xVel; } else { xPos += timeToBounceX * xVel; xVel = -xVel * BOUNCE_RATIO; xPos += (DELAY_S - timeToBounceX) * xVel; } // find time till bounce in y direction double timeToBounceY = Double.MAX_VALUE; if (yVel > 0) { timeToBounceY = (height - yPos - RADIUS) / yVel; } else if (yVel < 0) { timeToBounceY = (yPos - RADIUS) / -yVel; } // update y position and velocity if(timeToBounceY > DELAY_S) { yPos += DELAY_S * yVel; yVel += DELAY_S * GRAVITY; } else { yPos += timeToBounceY * yVel; yVel = -yVel * BOUNCE_RATIO + (timeToBounceY * GRAVITY); yPos += (DELAY_S - timeToBounceY) * yVel; yVel += (DELAY_S - timeToBounceY) * GRAVITY; } } public void actionPerformed(ActionEvent arg0) { repaint(); } }