简体   繁体   中英

How to access a different row from a sprite sheet?

I am using a tutorial to understand how sprites work using a draw() method as well as using a gameloop. I adjusted the code as far as I understand it for my own project.

The question I have is how can I access a different row of my sprite sheet besides the second row. My sprite sheet has 9 columns and 20 rows.

public class Sprite implements Drawable {
    private static final int BMP_COLUMNS = 9;
    private static final int BMP_ROWS = 20;
    private int x = 0;
    private int y = 0;
    private int xSpeed = 5;
    private Bitmap bmp;
    float fracsect = 30;
    private GameContent gameContent;
    private int currentFrame = 0;
    private int width;
    private int height;


public Sprite(GameContent gameContent, Bitmap bmp) {
    this.gameContent = gameContent;
    this.bmp = bmp;
    this.width = bmp.getWidth() / BMP_COLUMNS;
    this.height = bmp.getHeight() / BMP_ROWS;
}

@Override
public void update(float fracsec) {
    if (x > gameContent.getGameWidth() - width - xSpeed) {
        xSpeed = -5;
    }
    if (x + xSpeed < 0) {
        xSpeed = 5;
    }
    x = x + xSpeed;
    currentFrame = ++currentFrame % BMP_COLUMNS;
}

@Override
public void draw(Canvas canvas) {
    update(fracsect);
    int srcX = currentFrame * width;
    int srcY = 1*height - 41;

    Rect src = new Rect(srcX +20 , srcY,srcX + width,srcY + height-38); // Generates
    Rect dst = new Rect(x,y,x+width -30, y+height-30); // Scales
    canvas.drawBitmap(bmp, src, dst, null);
    }
}

How do I gain access to the second row and how can I change it for instance to the third or 4th row ?

What I understand so far is that using a sprite as an object as a bitmap instead via imageview the code implementation of the code works differently. Is there any advice on how to access a different row for the sprite sheet ? I used the android documentation as well as the tutorial to understand this process as far as I can.

Here is the tutorial also: http://www.edu4java.com/en/androidgame/androidgame4.html

From what I can see you are iterating through the first row, drawing each sprite in turn, perhaps to create an animation.

If you want to draw the animation for the second row, you can simply add 'height' to 'srcY'. It looks like you had this idea but you substracted instead of adding. Remember that Y-coordinates on computers go from top to bottom (ie (0,0) is top-left, (0, 10) is 10 pixels lower).

Likewise for the third and fourth rows, just add 'height' to 'srcY' again.

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