here is the code that i have so far...
import java.applet.Applet;
import java.awt.*;
// The "Graphics" class.
public class BouncingBall extends Applet
{
final int WIDTH = 300;
final int HEIGHT = 180;
Button bounce = new Button ("Bounce Ball");
Canvas display = new Canvas ();
public void init ()
{
setLayout (new BorderLayout ());
add ("North", bounce);
display.resize (WIDTH, HEIGHT);
add ("Center", display);
}
public boolean action (Event e, Object o)
{
final int RADIUS = 10;
Graphics displayG;
int x;
int y;
int dx;
int dy;
displayG = display.getGraphics ();
displayG.setColor (Color.blue);
displayG.fillRect (0, 0, WIDTH, HEIGHT);
displayG.setColor (Color.black);
displayG.drawRect (0, 0, WIDTH, HEIGHT);
x = (int) (Math.random () * (WIDTH - 2 * RADIUS)) + RADIUS;
y = (int) (Math.random () * (HEIGHT - 2 * RADIUS)) + RADIUS;
drawBall (displayG, x, y, RADIUS, Color.red);
dx = 1;
dy = 1;
for (int i = 0 ; i <= 10000 ; i++)
{
drawBall (displayG, x, y, RADIUS, getBackground ());
x += dx;
y += dy;
if (x <= RADIUS || x >= WIDTH - RADIUS)
dx = -dx;
if (y <= RADIUS || y >= HEIGHT - RADIUS)
dy = -dy;
displayG.setColor (Color.blue);
displayG.fillRect (0, 0, WIDTH, HEIGHT);
drawBall (displayG, x, y, RADIUS, Color.red);
delay (100000);
}
Font f = new Font ("Serif", Font.BOLD, 72);
displayG.setColor (Color.white);
displayG.setFont (f);
displayG.drawString ("Done!", WIDTH / 2 - 80, HEIGHT / 2);
return true;
}
public void drawBall (Graphics g, int x, int y, int radius, Color clr)
{
g.setColor (clr);
g.fillOval (x - radius, y - radius, 2 * radius, 2 * radius);
}
public void delay (int howLong)
{
for (int i = 1 ; i <= howLong ; i++)
{
double garbage = Math.PI * Math.PI;
}
}
}
John - 22 Apr 2005 14:17 GMT
> here is the code that i have so far...
>
[quoted text clipped - 75 lines]
> }
> }
That's nice clean coding. Good effort.
If I were you I would create a separate method that dealt with
collisions. Every "step", you would call this method, and it would check
to see if the ball had hit a wall. It would then return the new velocity
of your ball. You could then extend this method so that it checks for
hitting a bat as well as for hitting a wall.
Get it working for a stationary bat, then look at moving the bat. The
standard way of doing this is to use the mouse. You can "listen" for
mouse movements and cause events to occur each time the mouse is moved
(like moving the bat for example). You may like to look at
java.awt.event.MouseMotionAdapter.
John