| Animation by Example: Using a
Background by David Matuszek |
It's very easy to use a background; just paint it before you paint the "sprites" (other objects, usually animated objects). However, this can cause flicker--maybe a lot of flicker. We'll take care of that next.
Here's the same applet as before, modified to paint a background:
Here are the changes I made to get this new applet. First, the update()
routine:
/**
* Paints a background, then paints other things on top of it.
*/
public void update(Graphics g) {
background(g); // This line is new
paint(g);
}
Here's the new background() routine:
/**
* Paints a background on the given Graphics.
*/
void background(Graphics g) {
int width = getSize().width;
int height = getSize().height;
int squareSize = 2 * model.BALL_SIZE;
g.setColor(Color.blue);
g.fillRect(0, 0, width, height);
g.setColor(Color.green);
for (int x = 0; x < width; x += 2 * squareSize) {
for (int y = 0; y < height; y += 2 * squareSize) {
g.fillRect(x, y, squareSize, squareSize);
g.fillRect(x + squareSize, y + squareSize, squareSize, squareSize);
}
}
}
Now, one more change was required. In the paint() routine I had
been keeping track of the old ball location, and "erasing" it by painting
a white square there; this code had to be removed.
int oldX, oldY;... /** * Repaints the canvas based on information that it gets from the model. */ public void paint(Graphics g) {// Erase previous ball (since update() no longer does this)g.setColor(Color.white);g.fillRect(oldX, oldY, model.BALL_SIZE, model.BALL_SIZE);// Draw new balland remember its positiong.setColor(Color.red); g.fillOval(model.xPosition, model.yPosition, model.BALL_SIZE, model.BALL_SIZE);oldX = model.xPosition;oldY = model.yPosition;// Display steps and position in the status line; // this is a good place to put debugging information. if(++stepNumber % 10 == 0) controller.showStatus("Step " + stepNumber + ", x = " + model.xPosition + ", y = " + model.yPosition); }
|
|
|