cs106a – Assignment #3 – Task #2

The complete specification of assignment #3 can be found as part of the stream at iTunes.

Create the paddle

The next step is to create the paddle. At one level, this is considerably easier than the bricks. There is only one paddle, which is a filled GRect. You even know its position relative to the bottom of the window.
The challenge in creating the paddle is to make it track the mouse. The technique is similar to that discussed in Chapter 9 for dragging an object around in the window. Here, however, you only have to pay attention to the x coordinate of the mouse because the y position of the paddle is fixed. The only additional wrinkle is that you should not let the paddle move off the edge of the window. Thus, you’ll have to check to see whether the x coordinate of the mouse would make the paddle extend beyond the boundary and change it if necessary to ensure that the entire paddle is visible in the window.


The paddle consists of a single rectangle positioned in the center of the given y position. In addition it will listen to the mouse movement:

	private void setupPaddle() {
		paddle = new GRect(PADDLE_WIDTH, PADDLE_HEIGHT);
		paddle.setLocation(
				(WIDTH - PADDLE_WIDTH) / 2, 
				HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT
		);
		paddle.setFilled(true);
		add(paddle);
		addMouseListeners();
	}

The paddle will only follow the horizontal movement, but will not leave the screen:

	public void mouseMoved(MouseEvent e) {
		double x = e.getX();
		double minX = PADDLE_WIDTH / 2;
		double maxX = WIDTH - PADDLE_WIDTH / 2;
		if (x < minX) {
			x = minX;
		} else if (x > maxX) {
			x = maxX;
		}
		paddle.setLocation(
				x - minX, 
				HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT
		);
	}

The code for this assignment is available on github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.