Can't get keyListener to work

edit: i decided to post screenshots instead to make it more readable. well… don’t laugh at me pls :smiley: i was trying to make a very simplistic game engine, lol. however… the keyPressed-function never seems to get called. my DBG()-messages never appear in the console. does anyone see the problem?

Unbenannt2

For future reference: there are two options for making code snippets readable on the forum

surround the code with three back ticks : `
or highlight the code and click the </> icon in the toolbar

then it will look like this:

   int someInt = 42;
   double someDouble = 23.0;

You could try grabKeyboardFocus() https://docs.juce.com/master/classComponent.html#a91886a0e276d27719fa8866a95306571

1 Like

awesome!

first of all, your solution worked. i wonder why this wasn’t mentioned in any of the other forum posts i read about the keyListener though. maybe there should be a general juce tutorial about this for newbies like me.

2ndly thanks for your introduction in how posting code snippets works. let me try that right now:

int blaze = 420;
float inc = 1.f/float(420);
if(inc>1)
	inc-=.5f;
1 Like

btw does anyone know how i can make the keys behave less like i’m trying to write in a textbox? you see i’m currently using the keypresses to move a little rectangle so when i press and hold it goes one step, waits a sec, and then does the hold thing where it moves constantly. i’d like it to skip this thing at the beginning and directly jump to the “moving constantly-state”

The key repeat is coming from the OS (where you can set a certain delay after which it starts to send additional keystrokes, typically 200 ms).
For a game engine you don’t want that, but instead you would use your own timer and check which key is pressed. Also I think it is better to use the information from keyStateChanged, because it doesn’t send the key repetitions. But I haven’t tested that aspect.

Or you can ignore the keyListener completely and use the static function in your timer:

void timerCallback() override
{
    // you might want to check, if not another component has focus
    if (hasKeyboardFocus() == false)
        return;

    if (KeyPress:isKeyCurrentlyDown (KeyPress::leftKey))
        moveSpaceShipLeft();
    if (KeyPress:isKeyCurrentlyDown (KeyPress::rightKey))
        moveSpaceShipRight();
}

This solution even allows multiple players using different keys…

2 Likes

awesome! this really creates a nice and even movement. i didn’t know the other method was sending out events all the time. i thought keyboard-inputs were more like midi, with a keyDown and keyUp-signal or so