import java.awt.*; public class BouncingBall { private Color color; private int radius; private double centerX, centerY; private double velocityX, velocityY; public BouncingBall(Color color, int centerX, int centerY, int radius) { this.color = color; this.centerX = centerX; this.centerY = centerY; this.radius = radius; do { velocityX = (int)(20*Math.random() - 10); velocityY = (int)(20*Math.random() - 10); } while (Math.abs(velocityY) <= 2 && Math.abs(velocityX) <= 2); } public void doFrame(Graphics g, int width, int height) { g.setColor(color); g.fillOval((int)centerX - radius, (int)centerY - radius, 4*radius, 4*radius); centerX += velocityX; centerY += velocityY; if (centerX - radius < 0) velocityX = Math.abs(velocityX); if (centerX + radius >= width) velocityX = -Math.abs(velocityX); if (centerY - radius < 0) velocityY = Math.abs(velocityY); if (centerY + radius >= height) velocityY = -Math.abs(velocityY); } public void setPosition(int x, int y) { this.centerX = x; this.centerY = y; } public void headTowards(int x, int y) { if (Math.abs(x - centerX) < 1.0E-10 && Math.abs(y - centerY) < 1.0E-10) return; double v = Math.sqrt(velocityX*velocityX + velocityY*velocityY); double d = Math.sqrt((x-centerX)*(x-centerX) + (y-centerY)*(y-centerY)); velocityX = (x-centerX)*v/d; velocityY = (y-centerY)*v/d; } }