I recently discovered the Java4k competition, after looking at a few of the games that were on the website, it began to amaze me how good they were. The thing that I am trying to get at is that looking at the games most of them involve use sprites, and after looking at some of the source code, I don’t quite understand how the images are done. Could any of you please explain how they do it. Thanks.
The way I’d do it is to just create an image then draw on it, but I’ve never done Java4k so I don’t know how the pros do it. Here is a very simple example.
// Create an image of the size you want
BufferedImage img = new BufferedImage(10, 10);
// Get the Graphics2D object for the image
Graphics2D g = img.createGraphics();
// Do all your drawing
g.setColor(Color.BLACK);
g.fillRect(0, 0, 10, 10);
http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html
If you using a .jar you will need to use something can track it’s position, for example .getResource().
Take a look at this.
http://www.java4k.com/index.php?action=games&method=view&gid=332
I have used, the simple g.draw/fill function a lot but these seem to do it a lot more effectively.
As the link above showed, one method is to use Image references:
// create a sprite image using alpha + RGB channels
BufferedImage sprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
You can then set the individual pixels from an int array:
setRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize)
sprite.setRGB(0, 0, width, height, pixel_array, 0, 8);
and draw it using Graphics.drawImage
.
The trick, then, is filling the pixels. These are encoded per integer as per-byte values:
pixel_array[offset + (y-startY)*scansize + (x-startX)] = (alpha_channel << 24) | (red_channel << 16) | (green_channel << 8) | blue_channel;
Likewise, you can use a single BufferedImage for the whole screen, and write directly to that, and draw it with one call to drawImage.
Thanks.