Pookie
Pookie

Reputation: 1279

Getting a specific row in a spritesheet libgdx java

I am trying to access a specific row in my sprite sheet and I am thoroughly confused as to how to do this. I tried modifying a tutorial I found to accomplish this but when I run the code the length of my animation array is of size 0 when there are five rows in my spritesheet and 12 columns. My class should always fill my animation array with one row of information. Here is my Animator class

    public Animator(Texture spriteSheet, int cols){
    this.walkSheet = spriteSheet;
    this.cols = cols;
    this.rows = 1;
}

public void create() {
      TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth()/cols, walkSheet.getHeight()/rows);              // #10
      walkFrames = new TextureRegion[cols];
      anim = new Animation[rows];
      for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
          walkFrames[j] = tmp[i][j];
        }
        anim[i] = new Animation(0.025f, walkFrames);
      }
      stateTime = 0f;                         // #13
    }

public void render(int index, SpriteBatch spriteBatch, int x, int y, int width, int height) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
    stateTime += Gdx.graphics.getDeltaTime();
    currentFrame = anim[index].getKeyFrame(stateTime, true);
    spriteBatch.draw(currentFrame, x, y, width, height);
}

Any help with this will be extremely appreciated as I have spent so much time trying to figure this out.

Upvotes: 0

Views: 139

Answers (1)

Jose Romero
Jose Romero

Reputation: 569

I haven't tried this code yet, but I think this could work for what you want.

public Animator(Texture spriteSheet, int cols, int rows){
    this.walkSheet = spriteSheet;
    this.cols = cols;
    this.rows = rows;
}

public void create() {
      TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth()/cols, walkSheet.getHeight()/rows);              // #10
      anim = new Animation[rows];
      for (int i = 0; i < rows; i++) {
       walkFrames = new TextureRegion[cols];
       for (int j = 0; j < cols; j++) {
          walkFrames[j] = tmp[i][j];
        }
      anim[i] = new Animation(0.025f, walkFrames);
      }
      stateTime = 0f;                         // #13
    }

public void render(int index, SpriteBatch spriteBatch, int x, int y, int width, int height) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
    stateTime += Gdx.graphics.getDeltaTime();
    currentFrame = anim[index].getKeyFrame(stateTime, true);
    spriteBatch.draw(currentFrame, x, y, width, height);
}

Upvotes: 1

Related Questions