How to use one PNG image for several sprites?

How to use one PNG image for multiple sprites? I am trying to make a simple 2d game and I do not want to have 20+ different image files. I just want to put them in a single PNG file.

Example

terrain.png (and items.png ) from minecraft has different tiles on it, and each 16x16 pixel area is used for a different block texture.

Can someone provide a code and explanation?

+4
source share
1 answer

I wrote a Java game a few years ago, so I hope you can get some helpful tips and code examples.

You can organize your sprites in one image as follows:

https://github.com/mikera/tyrant/blob/master/src/main/resources/images/creature32.png

The above example uses 32x32 sprites, you can use any size you like, but it helps to keep them in normal mode.

Then, when you draw the screen during the game, you simply select the appropriate sprite and draw in the right place.

The code might look something like this:

 public void drawImage(Graphics g,double x, double y, int image) { int px = (int)((x - scrollx) * TILEWIDTH); int py = (int)((y - scrolly) * TILEHEIGHT); int sx = (image%20) * TILEWIDTH; int sy = TILEHEIGHT * (image/20); g.drawImage(sourceImage, px, py, px + TILEWIDTH, py + TILEHEIGHT, sx, sy, sx + TILEWIDTH, sy + TILEHEIGHT, null); } 

Here int image is the index at the position on the used sprite sheet. An increment of 1 to move one sprite to the right, an increase of 20 to move one sprite on a sprite sheet.

More complete source code is available at: https://github.com/mikera/tyrant/blob/master/src/main/java/mikera/tyrant/MapPanel.java

+1
source

All Articles