GAMES LESSON SIX: Simple Animation
In order to create an animation you must redraw the screen repeatedly to
create the illusion of movement. You can draw animations using java draw
methods (such as drawLine, drawRect, fillOval, etc.) or you can load images
and alternate between different images. In this applet we load images and
then we set off an endless loop which creates the animation of a character
doing push ups. (The character doing push ups was created using The GIMP.)
In this applet we create a special inner, private class to handle each frame
of the animation:
private class AnimFrame{
Image image;
int duration;
public AnimFrame(Image i, int dur){
image=i;
duration = dur;
}
}
This inner class contains variables for an image and and integer. Instances
of this class are stored in an ArrayList. These images are retrieved from
the ArrayList using the getImage() method which is called during execution
of the run() method. The getDelay method is also called in the run() method.
You should take time to trace the complete execution of
this sample program.
ANIMATE.java
import java.awt.*;
import java.applet.*;
import java.util.*;
public class ANIMATE extends Applet implements Runnable{
int dur[] = { 200, 400, 300 , 600 };
String titles[] = { "up.jpg", "mid.jpg", "down.jpg" , "mid.jpg" };
Dimension d;
boolean iload=false;
Image offI;
Image currImage;
ArrayList frames;
int pnum, inum, frameIndex;
int delay = 3000;
Thread tt;
public void init(){
d = getSize();
frames = new ArrayList();
offI=createImage(d.width,d.height);
currImage = getImage(getDocumentBase(), "images/mid.jpg");
tt = new Thread(this);
tt.start();
}
public void loadImage(int c){
addFrame(getImage(getDocumentBase(), "images/"+titles[c]), dur[c]);
}
public void addFrame(Image i, int d){
frames.add(new AnimFrame(i, d));
}
public synchronized Image getImage(){
if(frames.size() == 0) return null;
else return getFrame(frameIndex).image;
}
private AnimFrame getFrame(int i){
return (AnimFrame)frames.get(i);
}
public synchronized int getDelay(){
if(frames.size() == 0) return 2000;
else return getFrame(frameIndex).duration;
}
public void run(){
while(true){
repaint();
if(iload==false){
loadImage(inum);
inum++;
if(inum>3) iload=true;
}
else{
currImage=getImage();
delay = getDelay();
frameIndex=(frameIndex+1)%4;
}
try{
Thread.sleep(delay);
}catch(InterruptedException ie){
}
}
}
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);
if(iload){
offG.drawImage(currImage,0,0, null);
offG.setColor(Color.blue);
offG.drawString("DELAY: " + delay, 30, 100);
}
else{
offG.setColor(Color.blue);
offG.drawString("Loading images..." + inum, 30, 100);
}
g.drawImage(offI,0,0,this);
}
private class AnimFrame{
Image image;
int duration;
public AnimFrame(Image i, int dur){
image=i;
duration = dur;
}
}
}
ASSIGNMENT: