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

后端 未结 4 1231
星月不相逢
星月不相逢 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条回答
  •  孤独总比滥情好
    2020-12-29 12:21

    In your game loop method (maybe render or make one) need to add an input handler (implementing InputProcessor). The class InputProcessor have methods like:

    public boolean keyDown (int keycode);
    
    /**
     * Called when a key was released
     * 
     * @param keycode one of the constants in {@link Input.Keys}
     * @return whether the input was processed
     */
    public boolean keyUp (int keycode);
    
    /**
     * Called when a key was typed
     * 
     * @param character The character
     * @return whether the input was processed
     */
    public boolean keyTyped (char character);
    

    and the class Input.Keys has a lot of static varibles as keycodes. For example:

            public static final int D = 32;
            public static final int A = 29;
            public static final int S = 47;
            public static final int W = 51;
    

    So, implement key* methods and check if some key are pressed and increment or decrement X/Y from mario.

    EDIT: Check this links: http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/InputProcessor.java http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/Input.java

    or, in trunk, how to a demos handle input: http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Fdemos

    Hope help

提交回复
热议问题