Skip to content

Instantly share code, notes, and snippets.

@NatashaTheRobot
Created November 10, 2011 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NatashaTheRobot/1354199 to your computer and use it in GitHub Desktop.
Save NatashaTheRobot/1354199 to your computer and use it in GitHub Desktop.
This is the solution to step 4 of the Stanford CS106A Breakout game assignment, checking for collisions off the paddle and brick
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;
}
//We don't need to check for the bottom wall, since the ball can fall through the wall at that point
if ((ball.getY() - vy <= 0 && vy < 0 )) {
vy = -vy;
}
//check for other objects
GObject collider = getCollidingObject();
if (collider == paddle) {
vy = -vy;
}
//since we lay down a row of bricks, the last brick in the brick wall is assigned the value brick.
//so we narrow it down by saying that the collier does not equal to a paddle or null,
//so all that is left is the brick
else if (collider != null) {
remove(collider);
vy = -vy;
}
pause (DELAY);
}
private GObject getCollidingObject() {
if((getElementAt(ball.getX(), ball.getY())) != null) {
return getElementAt(ball.getX(), ball.getY());
}
else if (getElementAt( (ball.getX() + BALL_RADIUS*2), ball.getY()) != null ){
return getElementAt(ball.getX() + BALL_RADIUS*2, ball.getY());
}
else if(getElementAt(ball.getX(), (ball.getY() + BALL_RADIUS*2)) != null ){
return getElementAt(ball.getX(), ball.getY() + BALL_RADIUS*2);
}
else if(getElementAt((ball.getX() + BALL_RADIUS*2), (ball.getY() + BALL_RADIUS*2)) != null ){
return getElementAt(ball.getX() + BALL_RADIUS*2, ball.getY() + BALL_RADIUS*2);
}
//need to return null if there are no objects present
else{
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment