Search code examples
javaandroidandroid-studiolibgdxdesktop-application

Animation appears only when key is pressed, image disappears when no key is pressed


The screen is blank when no key is pressed, I want the animation to stop at the last image of the animation, but it disappears when no key is pressed. Here is my render method.

public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    time += Gdx.graphics.getDeltaTime();
    if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
        batch.draw(right.getKeyFrame(time, true), 100, 0);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.LEFT))batch.draw(left.getKeyFrame(time,true),100,0);
    batch.end();
}

Solution

  • The problem is that you are not calling batch.draw(...) when neither RIGHT or LEFT are being pressed.

    You need something like:

    if ( Gdx.input.isKeyPressed(Input.Keys.RIGHT) )
    {
        batch.draw(right.getKeyFrame(time, true), 100, 0);
    }
    else if ( Gdx.input.isKeyPressed(Input.Keys.LEFT) )
    {
        batch.draw(left.getKeyFrame(time, true), 100, 0);
    }
    else
    {
        batch.draw(middle.getKeyFrame(time, true), 100, 0);
    }
    

    You need to replace the middle object with what you expect to see on the screen when no keys are pressed.