Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@NatashaTheRobot
Created November 9, 2011 23:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NatashaTheRobot/1353463 to your computer and use it in GitHub Desktop.
Save NatashaTheRobot/1353463 to your computer and use it in GitHub Desktop.
This is the solution to step 3 of the Stanford CS106A Breakout game assignment, creating a ball and making it bounce off the walls
//These are declared outside the method, but in the class.
/**Ball velocity*/
private double vx, vy;
/**Random number generator for vx*/
private RandomGenerator rgen = RandomGenerator.getInstance();
/** Animation delay or paust time between ball moves */
private static final int DELAY = 10;
//this part is inside the method.
//adding an individual ball object
private GOval ball;
//ball set-up
private void drawBall() {
double x = getWidth()/2 - BALL_RADIUS;
double y = getHeight()/2 - BALL_RADIUS;
ball = new GOval(x, y, BALL_RADIUS, BALL_RADIUS);
ball.setFilled(true);
add(ball);
}
private void playGame() {
waitForClick();
getBallVelocity();
while (true) {
moveBall();
}
}
private void getBallVelocity() {
vy = 3.0;
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(0.5)) {
vx = -vx;
}
}
private void moveBall() {
ball.move(vx, vy);
//check for walls
//need to get vx and vy at the point closest to 0 or the other edge
if ((ball.getX() - vx <= 0 && vx < 0 )|| (ball.getX() + vx >= (getWidth() - BALL_RADIUS*2) && vx>0)) {
vx = -vx;
}
if ((ball.getY() - vy <= 0 && vy < 0 ) || (ball.getY() + vy >= (getWidth() - BALL_RADIUS*2) && vy>0)) {
vy = -vy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment