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\$
  • \$\begingroup\$ can you add more details? "doesn't seem to work"? \$\endgroup\$ – ronscript Oct 12 '16 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\$ – MagnusSchuldiner Oct 12 '16 at 19:24
  • \$\begingroup\$ can you write your whole code \$\endgroup\$ – ronscript Oct 12 '16 at 20:33
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\$
  • \$\begingroup\$ should I add it necessary in the update() mehtod? \$\endgroup\$ – MagnusSchuldiner Oct 12 '16 at 19:24
  • \$\begingroup\$ @MagnusSchuldiner yes, if you are gonna toggle show and hide of sprite \$\endgroup\$ – ronscript Oct 12 '16 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.