0
\$\begingroup\$

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();
}
\$\endgroup\$
3
  • \$\begingroup\$ can you add more details? "doesn't seem to work"? \$\endgroup\$
    – ronscript
    Oct 12, 2016 at 0:23
  • \$\begingroup\$ what I mean is that with that code the sprite is not drawn and I don't get it why \$\endgroup\$ Oct 12, 2016 at 19:24
  • \$\begingroup\$ can you write your whole code \$\endgroup\$
    – ronscript
    Oct 12, 2016 at 20:33

2 Answers 2

1
\$\begingroup\$

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();
\$\endgroup\$
0
\$\begingroup\$

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();

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .