Wednesday, July 18, 2012

Bouncing ball.

This is a code snippet of a loop from "bouncing ball" problem, I have used acm.* library package. PAUSE_TIME (how often refreshed screen) is a named constant, in this example equals 1 (humans eyes don't see refresh rate less than 50), from this value as from dx, dy values depended ball's speed. Algorithm actually isn't complicated, all you need is to describe process of touching canvas borders mathematically but easy to forget change initial x, y coordinates for the next ball move. "ball" in that case graphical object GOval.

while (true) {
   if ((x > getWidth() - BALL_SIZE) || (x < 0))    dx = -dx; 
   if ((y > getHeight() - BALL_SIZE) || (y < 0))   dy = -dy;
   x += dx; y += dy; 
   ball.move(dx, dy); 
   pause(PAUSE_TIME); 
   }
Download ACM.JAR  (don't forget to click advertising :) and TUTORIAL HOW TO USE.

No comments:

Post a Comment