# Draw a sprite when a key is pressed in LibGDX

I'm working with LibGDX. How can I draw a sprite when a key is pressed? I have tried with the following, but it doesn't seem to work.

if (Gdx.input.isKeyPressed(Input.Keys.X)) {
batch.begin();
sprite.draw(batch);
batch.end();
}

• can you add more details? "doesn't seem to work"? – ronscript Oct 12 '16 at 0:23
• what I mean is that with that code the sprite is not drawn and I don't get it why – MagnusSchuldiner Oct 12 '16 at 19:24
• can you write your whole code – ronscript Oct 12 '16 at 20:33

You could have a boolean that you set to true when the key is pressed in your update method:

 boolean drawSprite;
if (Gdx.input.isKeyPressed(Input.Keys.X)) {
drawSprite = true;
}


And then in your render method:

batch.begin();
if(drawSprite == true) {
sprite.draw(batch);
}
batch.end();


I assume you are using Sprite class from libgdx and the sprite you created is working fine? And the only problem is you cannot show the sprite when a key is pressed.

@Override
public void update() {

// the input is pressed once even you are still holding the button.
if(Gdx.input.isJustKeyPressed(Input.Keys.X)) {
sprite.setVisible(true);
}

batch.begin();
sprite.draw(batch);
batch.end();

}

• should I add it necessary in the update() mehtod? – MagnusSchuldiner Oct 12 '16 at 19:24
• @MagnusSchuldiner yes, if you are gonna toggle show and hide of sprite – ronscript Oct 12 '16 at 20:31