Hello guys,
we are programming our first 2D Java game and are very inecperienced in the topic performance tuning. We are not sure why the performance is so bad (probably there are too many reasons), but it’s mainly about the Image Drawing. Before we used Images (png and jpg for the background) the performance was great and the game has run fast. About the game: It’s a 2d space shooter like space invaders.
Because we are quite sure that the images cause the problems the following codes are limited to the drawing methods…
Loading of the Images (example class Shot):
public class Shot extends Elements {
private BufferedImage[] shot = new BufferedImage[3];
String shotName;
File shotSound;
public Shot(...) {
File shotAnimation[] = new File[3];
switch (mode) {
case 0: shotName = "defaultshot"; width = 5; height = 5; break;
...
}
for(int i = 0; i < shotAnimation.length; i++) {
shotAnimation[i] = new File (shotName + i + ".png");
}
try {
for(int i = 0; i < shot.length; i++) {
shot[i] = ImageIO.read(shotAnimation[i]);
}
}
catch (IOException e) {}
}
// ...
public void paintComponent(Graphics g) {
if(getAlive() == true && counter < 3) {
g.drawRect(getXc(), getYc(), width, height); // for collision, nothing to do with the images / problems
g.drawImage(shot[counter], getXc(), getYc(), null);
delay++;
if(delay %15 == 0)
counter++;
if(counter == 3)
counter = 0;
}
}
We thought about loading all Images in another class and use them in the classes (shot, spaceship and so on…). Maybe this would be a performance push? We are not quite sure.
The class, whrere the paintComponent() is used (Level):
public void paintComponent(Graphics g) {
background.paintComponent(g);
spaceship.paintComponent(g);
boss.paintComponent(g);
for(int i = 0; i < shots.size(); i++) {
if(shots.get(i).getAlive() == true)
shots.get(i).paintComponent(g);
}
//...
}
We are using Arraylists. Maybe this is slowing down the Performance? But we thought its better to use dynamic arraylists than the static Arrays.
The main Problem could be the Main class:
ActionListener Update = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
repaint();
}
};
new javax.swing.Timer(10, Update).start();
We have to repaint the whole panel after a few milliseconds, because otherwise the frame or the panel doesnt update and we aren’t able to see the differences (moving ship, enemies, generates shots and so on). Everything is still and only updates, if the frame is minimized and again on the desktop.
Maybe there are another solutions for updating the frame / panel or loading the images (faster ones of course ;D ). So it would be great, if anyone out there could help us, but thanks for taking the time reading all this anyway. Of course we would be grateful for hints on the net, but the whole possibilities in using 2D and Images some kind of overwhelmed us, that’s why we decided to post something here.