I don’t know if this has been posted before, but I get some questions from my friends how I get such high frame rates on my 2D java games. This is the class I use:
/*
- SpriteManager.java
- Created on April 28, 2006, 11:28 AM
- To change this template, choose Tools | Options and locate the template under
- the Source Creation and Management node. Right-click the template and choose
- Open. You can then make changes to the template in the Source Editor.
*/
package bomberdolf;
import java.awt.;
import java.awt.image.;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
/**
*
-
@author Cyclonis Delta
*/
public class SpriteManager {private static SpriteManager instance = new SpriteManager();
private HashMap sprites = new HashMap();public static SpriteManager get() {
return instance;
}public Sprite getSprite(String ref) {
if (sprites.get(ref) != null) return (Sprite)sprites.get(ref);BufferedImage sourceImage = null; try { URL url = new URL("file:"+System.getProperty("user.dir")+"/gfx/"+ref); if (url == null) { fail("Can't find ref: "+ref); } sourceImage = ImageIO.read(url); } catch (IOException ex) { System.out.println("could not read url"); } GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
image.getGraphics().drawImage(sourceImage,0,0,null); Sprite sprite = new Sprite(image); sprites.put(ref,sprite);
return sprite;
}private void fail(String message) { System.err.println(message); System.exit(0);
}
}
/*
- Sprite.java
- Created on August 21, 2006, 10:31 PM
- To change this template, choose Tools | Options and locate the template under
- the Source Creation and Management node. Right-click the template and choose
- Open. You can then make changes to the template in the Source Editor.
*/
package bomberdolf;
import java.awt.*;
/**
*
-
@author Cyclonis Delta
*/
public class Sprite {Image img;
/** Creates a new instance of Sprite */
public Sprite(Image image) {
img = image;
}public void drawMe(Graphics2D gfx, int x, int y) {
gfx.drawImage(img, x, y, null);
}
}
And in any method that you want to draw a particular sprite you simply call:
SpriteManager.get().getSprite(currentImg).drawMe(gfx, (int)x+15, (int)y);
in which the currentImg is simply a string with the path to your gif image.
I hope it works for you. I got FPS sometimes as high as 400, although they usually hang around at say 200-300