I have an animation class ready for my game. I think there are some optimization issues in this classroom.
Let's say there are more than 10 living entities with the same animations in my game.
Although they all have different animation times, the pictures of their animations are the same. When the code is like this, instead of keeping 2 pictures in RAM, wouldn't 20 pictures be kept? Code;
Animation idle;
BufferedImage idle1,idle2;
ArrayList<Soldier> enemyArmyArray = new ArrayList<Soldier>();
ArrayList<Animation> armyIdleAnimations = new ArrayList<Animation>();
w_idleImage1 = ImageIO.read(getClass().getResource("/Data/idle1.png"));
w_idleImage2 = ImageIO.read(getClass().getResource("/Data/idle2.png"));
for(int z = 0 ; z <= 10 ; z++) {
Soldier s = new Soldier();
armyArray.add(s);
idle = new Animation();
idle.addFrame(idle1, 400);
idle.addFrame(idle2, 400);
armyIdleAnimations.add(idle);
}
and this is my animation class:
public class Animation {
private ArrayList frames;
private int currentFrame;
private long animTime; // long takes up more memory than int but can hold
// more accurate numbers.
private long totalDuration;
public Animation() {
frames = new ArrayList();
totalDuration = 0;
synchronized (this) {
animTime = 0;
currentFrame = 0;
}
}
public synchronized void addFrame(BufferedImage image, long duration) {
totalDuration += duration;
frames.add(new AnimFrame(image, totalDuration));
}
public synchronized void update(long elapsedTime) {
if (frames.size() > 1) {
animTime += elapsedTime;
if (animTime >= totalDuration) {
animTime = animTime % totalDuration;
currentFrame = 0;
}
while (animTime >= getFrame(currentFrame).endTime) {
currentFrame++;
}
}
}
public synchronized BufferedImage getImage() {
if (frames.size() == 0) {
return null;
} else {
return getFrame(currentFrame).image;
}
}
private AnimFrame getFrame(int i) {
return (AnimFrame) frames.get(i);
}
private class AnimFrame {
BufferedImage image;
long endTime;
public AnimFrame(BufferedImage image, long endTime) {
this.image = image;
this.endTime = endTime;
}
}
public int getCurrentFrame() {
return currentFrame;
}
public void setCurrentFrame(int currentFrame) {
this.currentFrame = currentFrame;
}
public long getAnimTime() {
return animTime;
}
public void setAnimTime(long animTime) {
this.animTime = animTime;
}
}