简体   繁体   中英

Map character to X and Y in png - JAVA

I have this png image:

角色图块地图

and a string, say "Hello World". In order to map texture coords for LWJGL, I need to know the X and Y position of each 16x16 character in the PNG. I am completely lost on how one would do that.. Anyone?

Start with something like this:

final int spriteWidth = 16;
final int spriteHeight = 16;

 ...

int rows = sheet.getWidth()/spriteWidth;
int cols = sheet.getHeight()/spriteHeight;

BufferedImage sheet = ImageIO.read(new File("\\a\b\\c\\sprite_file.png"));
BufferedImage[] images = new BufferedImage[rows * cols];
for(int y = 0; y < cols; y++) {
    for(int x = 0; x < rows; x++) {
        images[y * x] = sheet.getSubImage(x * rows, y * cols, spriteWidth, spriteHeight);
    }
 }
  • Then make final int variables like so:

    public static final int SPRITE_0 = 0;
    public static final int SPRITE_1 = 1;
    ...

and access like so:

images[SPRITE_0]


Edit:

taking into consideration what @MadProgrammer has stated, I would recommend that you split the image into two parts, like so:

spritesheet

(split at the red line)

and then simply altering the code to handle the two different parts. The code will remain the same except for the variables final int spriteWidth and final int spriteHeight . I'm sure you can handle this yourself.


Edit 2:

if you just want the x and y co-ords of the top left corner of each sprite, do the following:

final int spriteWidth = 16;
final int spriteHeight = 16;

...

int rows = sheet.getWidth()/spriteWidth;
int cols = sheet.getHeight()/spriteHeight;
Point[] spriteTopLeftCorner = new Point[rows * cols];
for(int y = 0; y < sheet.getHeight(); y += spriteHeight) {
    for(int x = 0; x < sheet.getWidth(); x += spriteWidth) {
        spriteTopLeftCorner[y/spriteHeight * x/spriteWidth] = new Point(y, x);
    }
}

you would ofcourse still need to make variables representing each sprite's index in this Array , otherwise you wouldn't know what sprite you are taking out.

  • Do this like so:

    public static final int SPRITE_0 = 0;
    public static final int SPRITE_1 = 1;
    ...

  • and access like so:

    spriteTopLeftCorner[SPRITE_0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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