How to move a sprite with the keyboard keys using libGDX?

后端 未结 4 1221
星月不相逢
星月不相逢 2020-12-29 12:17

i have just started using java and libgdx and have this code, very simply it prints a sprite onto the screen. This works perfectly, and i learnt a lot from it.



        
4条回答
  •  旧时难觅i
    2020-12-29 12:24

    You can use the interface KeyListener to detect keyboard action.

    public class Game implements ApplicationListener, KeyListener {
    
    @Override
    public void create() {
        //Important
        this.addKeyListener(this);
    
        // TODO Auto-generated method stub
        batch = new SpriteBatch();
    
        FileHandle marioFileHandle = Gdx.files.internal("mario.png"); 
        marioTexture = new Texture(marioFileHandle);
        mario = new Sprite(marioTexture, 0, 158, 32, 64);
    
        marioX = 0;
        marioY = 0;
    
    
    }
    
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == 68) { //it's the 'D' key
                //Move your mario
            }
        }
    
    }
    

提交回复
热议问题