Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is the solution to step 2 of the Stanford CS106A Breakout game assignment, creating a paddle and making it track with the mouse.
//adding individual paddle object
private GRect paddle;
private double lastX;
//paddle set-up
private void drawPaddle() {
//starting the paddle in the middle of the screen
double x = getWidth()/2 - PADDLE_WIDTH/2;
//the paddle height stays consistent throughout the game
//need to make sure to subtract the PADDLE_HEIGHT,
//since the rectangle gets drawn from the top left corner
double y = getHeight() - PADDLE_Y_OFFSET - PADDLE_HEIGHT;
paddle = new GRect (x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
add (paddle);
//making the mouse track the paddle
public void mouseMoved(MouseEvent e) {
lastX = e.getX();
/* The mouse tracks the middle point of the paddle.
* If the middle point of the paddle is between half paddle width of the screen
* and half a paddle width before the end of the screen,
* the x location of the paddle is set at where the mouse is minus half a paddle's width,
* and the height remains the same
if ((e.getX() < getWidth() - PADDLE_WIDTH/2) && (e.getX() > PADDLE_WIDTH/2)) {
paddle.setLocation(lastX - PADDLE_WIDTH/2, getHeight() - PADDLE_Y_OFFSET - PADDLE_HEIGHT);
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.