/* Joonistab palli, kindla raadiusega*/ import java.awt.*; public class BouncingBall { public Color color; // palli värv private int radius; // palli raadius private double centerX, centerY; // keskkoha asukoht private double velocityX, velocityY; public BouncingBall(Color color, int centerX, int centerY, int radius) { // teeb uue palli vastavate omadustega, velocity jääb -10 ja 10 vahele, olles suure kui 3 (abs) 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) <= 3 && Math.abs(velocityX) <= 3); } public void doFrame(Graphics g, int width, int height) { //kutsutakse välja iga raamis, kui välja läheb pöörab tagasi g.setColor(color); g.fillOval((int)centerX - radius, (int)centerY - radius, 2*radius, 2*radius); centerX += velocityX; centerY += velocityY; if (centerX - radius < 0) { //play(getCodeBase(), "tap2.au"); velocityX = Math.abs(velocityX); } if (centerX + radius >= width) { //play(getCodeBase(), "tap2.au"); velocityX = -Math.abs(velocityX); } if (centerY - radius < 0) { //play(getCodeBase(), "tap2.au"); velocityY = Math.abs(velocityY); } if (centerY + radius >= height) { //play(getCodeBase(), "tap2.au"); velocityY = -Math.abs(velocityY); } } public void setPosition(int x, int y) { // Change position of the ball's center to the specified point, (x,y). this.centerX = x; this.centerY = y; } public void headTowards(int x, int y) { // Modify the velocity so that the ball is moving in the direction // of the point (x,y). The speed of the ball does not change, only // its direction of motion. (If the specified point is too close // to the current position of the ball, the velocity of the ball // does not change.) This method uses some standard vector mathematics. 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; } } // end class BouncingBall