import java.applet.Applet; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; /** * Draw a series of images of a "bouncing" ball. All will appear * at once (this is not an animation). Requires further development * by the student. * * @author Samuel A. Rebelsky * @version 1.0 of August 1999 */ public class Bounce extends Applet { /** Paint the series of images. */ public void paint(Graphics paintBrush) { int repetitions; // The number of images to show. int horiz=0; // The horizontal position of the center of the ball. int vert=0; // The vertical position of the center of the ball. int horizVelocity; // The horizontal velocity of the ball. int vertVelocity; // The vertical velocity of the ball (larger is down). int acceleration; // Downward acceleration due to gravity. int elasticity; // A number between 0 and 100 that represents // how much the ball bounces when it hits the floor. // 0 is "thud". 100 is "superball". int left = 0; // The left edge of the applet's area. int top = 0; // The top edge of the applet's area. int right; // The right edge of the applet's area. int bottom; // The bottom edge of the applet's area. // Compute the right and bottom edges. Dimension dim = this.getSize(); right = dim.width; bottom = dim.height; // Set the background color. setBackground(Color.white); // Read in the parameters. try { repetitions = Integer.parseInt(getParameter("repetitions")); } catch (Exception e) { repetitions = 100; } try { horizVelocity = Integer.parseInt(getParameter("horizVelocity")); } catch (Exception e) { horizVelocity = 10; } try { vertVelocity = Integer.parseInt(getParameter("vertVelocity")); } catch (Exception e) { vertVelocity = 10; } try { acceleration = Integer.parseInt(getParameter("acceleration")); } catch (Exception e) { acceleration = 1; } try { elasticity = Integer.parseInt(getParameter("elasticity")); } catch (Exception e) { elasticity = 100; } // And go. Note that this does not yet make the ball bounce. for (int step = 1; step <= repetitions; ++step) { // Draw the ball (a filled circle). paintBrush.fillOval(horiz-5,vert-5,11,11); // Check bouncing at edges if ( ((horiz > right-5) && (horizVelocity > 0)) || ((horiz < 5) && (horizVelocity < 0)) ) { horizVelocity = - horizVelocity; } if ((vert > bottom) && (vertVelocity > 0)) vertVelocity = - vertVelocity * 9/10; // Update the position. horiz = horiz + horizVelocity; vert = vert + vertVelocity; // Update the speed. vertVelocity = vertVelocity + acceleration; } // for(step) } // paint(Graphics) } // class Bounce