GAMES LESSON THIRTEEN: Moving Background

Imagine a game in which you look down upon a street map of a city. The map is bigger than the screen area and so it is necessary to adjust the map to allow for game movement which goes beyond the portion of the map which is currently visible on the screen.

In the sample applet an image is displayed which is larger than the applet area and the mouse can be used to change the portion of the image which is visible. The applet area is made small on purpose so that the user must use the mouse to explore the picture.

The portion of the code responsible for moving the picture is in the mouseMoved method:

public void mouseMoved(MouseEvent m) { newx = m.getX(); newy = m.getY(); if(newx>oldx) x+=3; else if(newx<oldx) x-=3; if(newy>oldy) y+=3; else if(newy<oldy) y-=3; if(x<-150) x=-150; if(x>0) x=0; if(y<-150) y=-150; if(y>0) y=0; oldx=newx; oldy=newy; repaint(); }

HUCK.java

import java.awt.*; import java.applet.*; import java.awt.event.*; public class HUCK extends Applet { Dimension d; Image offI; Image image; int x, y, oldx, oldy, newx, newy; public void init(){ d = getSize(); oldx=(int)d.getWidth()/2; oldy=(int)d.getHeight()/2; offI=createImage(d.width,d.height); image = getImage(getDocumentBase(), "images/huckleberry.jpg"); this.addMouseMotionListener(new MouseMotionAdapter(){ public void mouseMoved(MouseEvent m) { newx = m.getX(); newy = m.getY(); if(newx>oldx) x+=3; else if(newx<oldx) x-=3; if(newy>oldy) y+=3; else if(newy<oldy) y-=3; if(x<-150) x=-150; if(x>0) x=0; if(y<-150) y=-150; if(y>0) y=0; oldx=newx; oldy=newy; repaint(); } }); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Graphics offG = offI.getGraphics(); offG.drawImage(image,x,y,this); g.drawImage(offI,0,0,this); } }


ASSIGNMENT: