GAMES LESSON EIGHT: Sprites
A sprite can be an image or it can be something drawn using the Java draw
and fill methods. In this example we use the fillOval method to draw a
simple oval that bounces around the applet area like a little ball in a
rectangular chamber. The run method contains the only code of interest in
this example. Examine it well.
import java.awt.*;
import java.applet.*;
public class SPRITE extends Applet implements Runnable{
Dimension d;
Image offI;
Thread tt;
int xDIR=4;
int yDIR=4;
int xLOC=20;
int yLOC=5;
public void init(){
d = getSize();
offI=createImage(d.width,d.height);
tt = new Thread(this);
tt.start();
}
public void run(){
while(true){
if(xDIR>0 && xLOC>d.width-15 ||
xDIR<0 && xLOC<0 ) xDIR*=-1;
if(yDIR>0 && yLOC>d.height-15 ||
yDIR<0 && yLOC<0) yDIR*=-1;
xLOC+=xDIR;
yLOC+=yDIR;
try{
Thread.sleep(50);
}catch(InterruptedException ie){
}
repaint();
}
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
Graphics offG = offI.getGraphics();
offG.setColor(Color.yellow);
offG.fillRect(0,0,d.width,d.height);
offG.setColor(Color.blue);
offG.fillOval(xLOC,yLOC,15,15);
g.drawImage(offI,0,0,this);
offG.dispose();
}
}
ASSIGNMENT: