Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.