简体   繁体   中英

How to get subImages from a sprite sheet with different sprite sizes?

I'm doing a fighting game in Java, and I'm having some trouble with the animations.

The thing is when a player is idle or walking, I've no problem because every sprite has a fixed width (50px), but when the player attacks the sprite becomes wider as long as the punch goes further. And in-game the sprite doesn't draw correctly.

PS: I'm saving every frame/sprite inside an arraylist, and I change MAXFRAMES manually depending on the number of sprites. SS is the spritesheet.

I'm using getSubImage method as below.

public void setAnimacionIdleRight(BufferedImage ss) {
    this.animation_idle_right = new ArrayList<BufferedImage>();

    BufferedImage tmp = ss.getSubimage(0, 0, 350, 100);
    BufferedImage subtmp = null;
    int k = 1;
    for(int i = 1; i < MAXFRAMES; i++) {
        subtmp = tmp.getSubimage((CELLWIDTH * i) + k - CELLWIDTH, 1, CELLWIDTH, CELLHEIGHT);            
        this.animation_idle_right.add(subtmp);
        k++;
    }
}

SpriteSheet example:

例

Any Ideas? Or is the solution brute force img loading?

As sugested by MadProgrammer, you can manually set the size of each sprite in the sheet. Since the height is always the same, then you can simply have an array with the size of the number of sprites on the sheet, and put only sprite width in it.

To help you you could do a loop before manually setting the values like this:

float cellWidths[MAX_FRAMES/CELLNUMBER];
for(int i=0; i<MAX_FRAMES/CELLNUMBER;i++){
    cellWidths[i] = CELLWIDTH;
}
//set non default values manually.

and then you would only need to change you for like this:

for(int i = 1; i < MAXFRAMES; i++) {
    subtmp = tmp.getSubimage((cellWidths[i-1] * i) + k - cellWidths[i-1], 1, cellWidths[i-1], CELLHEIGHT);            
    this.animation_idle_right.add(subtmp);
    k++;
}

But i may be misunderstanding what MAX_FRAMES mean.

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