简体   繁体   中英

Java Game Dev: Sprite sheet frame by row and column?

I'm trying to figure out how to get the X and Y coords of the frames of an animated sprite sheet by giving it the frame width, height, rows, columns, and frameCount. Then I want it to give me back what row and column number the frame is in given a frameNumber. (counting from top to bottom right to left)

I realized that I could get the column number (if I consider the rows and columns to be represented by an int[][] ) just by doing frameNumber % rows but I'm stumped on how to get the row number. Any ideas?

If you have cols columns, you can simply use:

Use:

row = Math.floor(frameNumber / cols);
col = frameNumber % cols;

so if you have 1000 cols and want frame number 3989 it would give you:

row = 3; col = 989;

If you know the width and height of the frames, how many frames per row there are, and which frame you want, than getting the x and y coordinates is fairly simple:

    frameX = ((frameNumber - 1) % columns) * frameWidth;

    frameY = ((frameNumber - 1) / columns) * frameHeight;

Note that the '/' operation must be an int , short , or byte division, as you need the remainder to be rounded off to get the X and Y coordinates at the beginning of the frame, as opposed to somewhere in the middle.

These formulas are for a sprite sheet where the frames go from left to right, then top to bottom. If you want it the other way around, than just switch the '%' and '/' operators, and change 'columns' to 'rows':

    frameX = ((frameNumber - 1) / rows) * frameWidth;

    frameY = ((frameNumber - 1) % rows) * frameHeight;

This is also assuming that you will be referencing your frames starting at 1, however if you instead index them starting at 0, than the '- 1' portion can be removed:

    frameX = (frameNumber % columns) * frameWidth;

    frameY = (frameNumber / columns) * frameHeight;
    //assuming that frameNumber indexes from 0;

Also, if you just want to know which column or row the frame is in, than just remove the '* frameWidth' and '* frameHeight' portions, which will return row and column indices starting at 0:

    frameX = (frameNumber - 1) % columns;

    frameY = (frameNumber - 1) / columns;

Hope this helps.
Zistack

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