The idea is to create an Array (or a Vector if you don’t want a fixed size), which would hold your enemy classes, and then, of course, write the actual enemy class to control the enemy. Here’s something for you:
// First create an array big enough to hold the
// amount of enemys you want or need.
Enemy enemys[] = new Enemy[5]; // Holds 5 enemys
// You'll also need to create the Enemy Class,
// like the following:
public class Enemy extends Applet {
int x = 0;
int y = 0;
int dirx = 0;
int diry = 0;
int speed = 0;
int minX = 0;
int maxX = 0;
int minY = 0;
int maxY = 0;
int width = 0;
int height = 0;
double frame = 0;
Image frames[] = new Image[3];
ImageObserver observer;
public Enemy(int posX, int posY, int dx, int dy, int spd, int nminX, int nmaxX, int nminY, nmaxY, int enemyID, ImageObserver ob) {
observer = ob;
for (int i=0; i<frames.length; i++) {
frames[i] = getImage(getCodeBase(), "enemy"+enemyID+"_"+i+".png");
}
x = posX;
y = posY;
dirx = dx;
diry = dy;
speed = spd;
width = frames[0].getWidth(observer);
height = frames[0].getHeight(observer);
minX = x+nminX;
maxX = x+nmaxX;
minY = y+nminY;
maxY = y+nmaxY;
}
public void update(Graphics g) {
frame += 0.2;
if (frame >= frames.length) frame = 0;
x += speed*dirx;
y += speed*diry;
if (x <= minX) dirx *= -1;
if (x >= maxX) dirx *= -1;
if (y <= minY) diry *= -1;
if (y >= maxY) diry *= -1;
g.drawImage(frames[(int)frame], x, y, ob);
}
}
Here’s an example of creating an enemy:
enemys[0] = new Enemy(40, 40, 1, 0, -100, 100, 0, 0, 0, this);
Then when you need to update and draw the enemy, in your game loop, call the update method. Like this:
enemys[0].update(g);
Where g represents the Graphics context to which image/applet your drawing on to.
I haven’t tested this class, but it should work. Hopefully. I’m sure it’s pretty self explanatory, but if it isn’t just ask.