Pim Schwippert
Pim Schwippert

Reputation: 105

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

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?

Upvotes: 5

Views: 3104

Answers (1)

mikera
mikera

Reputation: 106391

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

Upvotes: 2

Related Questions