001package algs11;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac BouncingBall.java
005 *  Execution:    java BouncingBall
006 *  Dependencies: StdDraw.java
007 *
008 *  Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
009 *
010 *  % java BouncingBall
011 *
012 *************************************************************************/
013
014public class XBouncingBall {
015        public static void main(String[] args) {
016
017                // set the scale of the coordinate system
018                StdDraw.setXscale(-1.0, 1.0);
019                StdDraw.setYscale(-1.0, 1.0);
020
021                // initial values
022                double rx = 0.480, ry = 0.860;     // position
023                double vx = 0.015, vy = 0.023;     // velocity
024                double radius = 0.05;              // radius
025
026                // main animation loop
027                while (true)  {
028
029                        // bounce off wall according to law of elastic collision
030                        if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx;
031                        if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy;
032
033                        // update position
034                        rx = rx + vx;
035                        ry = ry + vy;
036
037                        // clear the background
038                        StdDraw.setPenColor(StdDraw.GRAY);
039                        StdDraw.filledSquare(0, 0, 1.0);
040
041                        // draw ball on the screen
042                        StdDraw.setPenColor(StdDraw.BLACK);
043                        StdDraw.filledCircle(rx, ry, radius);
044
045                        // display and pause for 20 ms
046                        StdDraw.show(20);
047                }
048        }
049}