6
\$\begingroup\$

Im making a game in LWJGL 2 and Slick2d. Im trying to add an item to my inventory by releasing a key (the inventory system works properly, the part where I have to see if the button was RELEASED is difficult). Right now when I do...

if (Keyboard.getEventKey() == Keyboard.KEY_L) {
    if(Keyboard.getEventKeyState() == false){
        Inventory.addItem(1);
    }
}

... In my update method, Instead of it only calling the 2nd if statement once, ( because you can only release a key once) It just keeps going because the getEventKeyState variable stays false, but if Ive already released it once it should switch back to the opposite. Although I can do it by making it add an item when i hold the key, I cant exactly make it add only the 1 item, it keeps adding items while I hold it.

public static void addItem(int id){
    for(InventorySlot s : inventoryslots){
        if(s.getItem() == -1){
            s.setItem(id);
            System.out.println("Added item " + id + "!");
            break;
        }
    }
}

Thats the addItem method, and if I would approach this by making it add the item while holding, I would have to make it so that it adds it only once. Any suggestions please? Thank you

\$\endgroup\$
  • \$\begingroup\$ Your problem lies in your keyreleased event. When you hold a key, it calls the keypressed event every frame update as long as the key is held down. When you call keyreleased, your key state will be false as long as you aren't pressing the key. I believe Slick2D recommends using @Vokail 's answer. See slick.ninjacave.com/wiki/index.php?title=Input \$\endgroup\$ – Nathaniel D. Hoffman Aug 16 '16 at 12:28
  • \$\begingroup\$ Also, if you do insist on using keystates, which are recommended by LWJGL and technically more useful, I would recommend reading (or rereading) wiki.lwjgl.org/wiki/LWJGL_Basics_2_(Input). You really need to be bounding your input with "while(Keyboard.next()) {...}" and I would recommend switching the order of the if-statements in the code you posted just for clarity. \$\endgroup\$ – Nathaniel D. Hoffman Aug 16 '16 at 12:33
0
\$\begingroup\$

You can use also container reference, getInput and check if a key is pressed, down, etc..

For example:

container.getInput().isKeyPressed(Input.KEY_SPACE)

see more details on javadoc

\$\endgroup\$

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.