简体   繁体   English

如何为多个精灵使用一个PNG图像?

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

How do I use a single PNG image for multiple sprites? 如何为多个精灵使用单个PNG图像? I'm trying to make a simple 2d game and I don't want to have like 20+ different image files. 我正在尝试制作一个简单的2D游戏,我不想拥有20多个不同的图像文件。 I just want to put them on one PNG file. 我只是想把它们放在一个PNG文件上。

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. 来自minecraft的terrain.png (和items.png )上有不同的图块,每个16x16像素区域用于块的不同纹理。

Can someone provide some code and an explanation? 有人可以提供一些代码和解释吗?

I wrote a Java game a few years back so hopefully can give you some useful advice and code samples.. 几年前我写了一个Java游戏,希望能给你一些有用的建议和代码示例。

You can organise your sprites in a single image like this: 你可以在一个图像中组织你的精灵,如下所示:

https://github.com/mikera/tyrant/blob/master/src/main/resources/images/creature32.png 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. 上面的例子使用32x32精灵,你可以使用你喜欢的任何尺寸,但它有助于保持它们的规律。

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. 这里int image是要使用的sprite表上的位置的索引。 Increment by 1 to move one sprite to the right, increment by 20 to move one sprite down in the sprite sheet. 递增1以向右移动一个精灵,递增20以在精灵表中向下移动一个精灵。

More complete source code available at: https://github.com/mikera/tyrant/blob/master/src/main/java/mikera/tyrant/MapPanel.java 更完整的源代码可从以下网址获得: https//github.com/mikera/tyrant/blob/master/src/main/java/mikera/tyrant/MapPanel.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM