Monday, October 8, 2018

opengl - LWJGL multiple keyboard/mouse input checks


As in many game libraries such as LWJGL, you can check mouse/keyboard events with Mouse.isButtonDown or Keyboard.IsKeyDown.


I want to check for button/key presses, not if it's currently pressed down (if that makes any sense) so I use Keyboard.next() and Mouse.next(). This works fine, except if you have multiple places where you want to do this check.


So if you do Mouse.next once for all the events in the 'queue', the queue is empty and future Mouse.next's don't return anything.


What would be the solution for this? Create a wrapper around the Keyboard class and save the keystate? If so, how can I save that state? Couldn't find anything in the javadocs.


Thanks in advance.



Answer



Accordingly to http://legacy.lwjgl.org/javadoc/org/lwjgl/input/Keyboard.html you can make this like this:


while (Keyboard.next())

{
bool pressed = Keyboard.getEventKeyState();
int key = Keyboard.getEventKey();
if(pressed) processKeyPress(key);
else processKeyRelease(key);
}

For more detail, you can google "Buffered input vs Unbuffered input" Buffered is when you receive the events of what happened, and unbuffered is when you have to poll the key state with "isKeyDown" at every frame.


Edit:


For being able to use the events in more than one place, do the following:



class KbEvent
{
public final bool Press;
public final int KeyID;
public KbEvent(bool press, int keyID)
{
Press = press; KeyID = keyID;
}
}


//On your game definition
Vector KeyboardEvents;

//On your game loop
KeyboardEvents.clear();
while (Keyboard.next())
{
KeyboardEvents.add(new KbEvent(Keyboard.getEventKeyState(), Keyboard.getEventKey()));
}


//Wherever you want to read all keyboard input:
for (KbEvent ev : KeyboardEvents)
{
if(ev.Press) processKeyPress(ev.KeyID);
else processKeyRelease(ev.KeyID);
}

practically the same extends for mouse, with just more variables.


This way, you'll save the current frame events elsewhere, and the re-use them everywhere you want. I don't know exactly HOW java handles the Vector class, but on C++ this should have no impact on frame rate.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...