Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use one single PNG image for multiple sprites?

Tags:

java

image

png

How do I use a single PNG image for multiple sprites? I'm trying to make a simple 2d game and I don't want to have like 20+ different image files. I just want to put them on one PNG file.

Example

The terrain.png (and items.png) from minecraft has different tiles on it and each of the 16x16 pixel areas are used for a different texture of a block.

Can someone provide some code and an explanation?

like image 888
Pim Schwippert Avatar asked Nov 03 '22 16:11

Pim Schwippert


1 Answers

I wrote a Java game a few years back so hopefully can give you some useful advice and code samples..

You can organise your sprites in a single image like this:

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

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

Then when you draw the screen during the game, you just pick off the respective sprite and draw in in the right location.

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 the int image is an index into the position on the sprite sheet to use. Increment by 1 to move one sprite to the right, increment by 20 to move one sprite down in the sprite sheet.

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

like image 189
mikera Avatar answered Nov 15 '22 01:11

mikera