Yeah I send it to sleep when the window is not focused, so it would not use 100% of the CPU.
I am using Java2D and I use translucent images. I load each image, create a translucent counterpart and make all the pink pixels transparent.
Here’s some of the stuff I do, if anyone notices what I should change just let me know.
JFrame initialization:
public Game() {
super(Settings.getProperty("game.title"));
setResizable(false);
setBounds(0,0,Globals.RESOLUTION_X,Globals.RESOLUTION_Y);
setSize(Globals.RESOLUTION_X, Globals.RESOLUTION_Y);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setIgnoreRepaint(true);
gc.setLayout(null);
setUndecorated(true);
gc.setBackground(Color.BLACK);
}
Graphics mode initialization. First I check whether it should be fullscreen or not, then I set the display mode to 800x600x32
/** Initialize buffers and fullscreen */
private void initGraphics() {
if (Settings.getPropertyBool("display.fullscreen")) {
if (Globals.GRAPHICS_DEVICE.isFullScreenSupported())
Globals.GRAPHICS_DEVICE.setFullScreenWindow(this);
DisplayMode[] displayModes = Globals.GRAPHICS_DEVICE.getDisplayModes();
int selected = 0;
for (int i=0; i<displayModes.length; i++) {
if (displayModes[i].getWidth() == Globals.RESOLUTION_X &&
displayModes[i].getHeight() == Globals.RESOLUTION_Y &&
displayModes[i].getBitDepth() == Globals.BPS)
selected = i;
}
Globals.GRAPHICS_DEVICE.setDisplayMode(displayModes[selected]);
}
createBufferStrategy(2);
}
I load images and make them transparent like this:
public static Color TRANSPARENT_COLOR = new Color(255,0,255);
private static HashMap pictures = new HashMap();
public static Image createTransparentImage(String path) throws IOException {
// no need to load the image twice
if (pictures.containsKey(path))
return (Image)pictures.get(path);
File file = new File(path);
if (!file.exists())
throw new IOException("File not found: " + path);
BufferedImage image = ImageIO.read(file);
BufferedImage result = Globals.GRAPHICS_CONFIG.createCompatibleImage(image.getWidth(),image.getHeight(),Transparency.TRANSLUCENT);
Graphics g2 = result.getGraphics();
// draw image on the transparent image
g2.drawImage(image,0,0,null);
g2.dispose();
// make the pixels transparent
DataBuffer dbuffer = result.getRaster().getDataBuffer();
// get array of pixels
int[] imageData = ((DataBufferInt)dbuffer).getData();
int r,g,b;
int red = TRANSPARENT_COLOR.getRed();
int blue = TRANSPARENT_COLOR.getBlue();
int green = TRANSPARENT_COLOR.getGreen();
for (int i=0; i<imageData.length; i++) {
r = getR(imageData[i]);
g = getG(imageData[i]);
b = getB(imageData[i]);
if ( (r == red) && (b == blue) && (g == green) ) {
imageData[i] = 0; // set pixel to 0 (also sets its alpha to 0)
}
}
pictures.put(path, result);
return result;
}
I tried changing the Transparency.TRANSLUCENT to Transparency.BITMASK but this only made the game improve to 16 fps