2
votes

In LibGDX, I'm making a sprite-based animation for my characters. I have a TextureRegion for the current frame and every time I draw the sprite I want to change the sprite's texture to the current frame. Here's the code I currently have.

TextureRegion currentFrame;
Sprite sprite;

and this:

@Override
public void draw(SpriteBatch batch) {
    if (batch.isDrawing()) {
        sprite.setTexture(currentFrame); <-- This line
    }
}

but on "this line" I get an error saying I can't set the sprite's texture to a texture region, so what I think I need to do is to convert the TextureRegion to a Texture so I can set the sprite to it. How would I do this?

2

2 Answers

2
votes

Ok, I guess that getTexture() method from TextureRegion class is not what you need in this case (otherwise you could simply use it like sprite.setTexture(currentFrame.getTexture());)

Since you're making an animation, I might guess that there is a sprite sheet image in your assets. So, to animate that sheet you should create a libgdx Animation like:

    int ROW = 4;  // rows of sprite sheet image
    int COLUMN = 4;
    TextureRegion[][] tmp = TextureRegion.split(playerTexture, playerTexture.getWidth() / COLUMN, playerTexture.getHeight() / ROW);
    TextureRegion[] frames = new TextureRegion[ROW * COLUMN];
    int elementIndex = 0;
    for (int i = 0; i < ROW; i++) {
        for (int j = 0; j < COLUMN; j++) {
            frames[elementIndex++] = tmp[i][j];
        }
    }
    Animation playerAnimation = new Animation(1, frames);

where playerTexture is your sprite sheet image

then in your character class you create TextureRegion currentFrame field to init current frame of your animation (playerAnimation above):

// used for currentFrame initialization
TextureRegion currentFrame = playerAnimation.getKeyFrame(0); 

then in update method of game screen you use float delta (or Gdx.graphics.getDeltaTime()) to update key frames of animation (in other words, to animate sprite).

public void update(float delta){
    currentFrame = playerAnimation.getKeyFrame(delta);
}

and finally in your draw (or render) method you draw char like

public void draw(){
    batch.begin();
    batch.draw(char.getCurrentFrame(), char.getPosition().x, char.getPosition().y);
    batch.end();
}

hope I understood your question correct and helped.

2
votes

Why don't you use setRegion(.......)?

sprite.setRegion(currentFrame);