This site requires JavaScript, please enable it in your browser!
Greenfoot back
Turbo_Thorsten
Turbo_Thorsten wrote ...

2021/6/18

Problem with getKey()

Turbo_Thorsten Turbo_Thorsten

2021/6/18

#
My code below only works with space, enter, control and so on. Why isn't working with a normal letter like k?
if (Greenfoot.getKey() == "k")
     {
         if (automove == false)automove = true;
         else automove = false;
     }
     if (automove == true)
     {
        showText("test", 200, 200);
     }
     if (automove == false)
     {
        showText(" ", 200, 200);
     }
Gbasire Gbasire

2021/6/18

#
you can use isKeyDown :
if (Greenfoot.isKeyDown("k"))
{
    //do stuff
}
Turbo_Thorsten Turbo_Thorsten

2021/6/18

#
But then this triggers every act and it's working perfectly fine with enter. Is there a way to use getKey with a normal letter?
Gbasire Gbasire

2021/6/18

#
hmm, I really don't know sorry, I never tried getKey(), did you try putting "k" in capital letter : "K" ?
Turbo_Thorsten Turbo_Thorsten

2021/6/18

#
I did it with isKeyDown but yes I tried different things but nothing worked.
Super_Hippo Super_Hippo

2021/6/18

#
You can try this:
String key = Greenfoot.getKey();
if ("k".equals(key))
{
    automove = !automove;
    showText(automove ? "test" : " ", 200, 200);
}
else if ("enter".equals(key))
{
    //...
}
Generally, the “getKey” method is a good option for text input, but not so much for gameplay mechanics. General advise: Make sure to never call the “getKey” method more than once per act cycle because it will only work once.
Turbo_Thorsten Turbo_Thorsten

2021/6/21

#
Your solution also only works with enter
Gbasire Gbasire

2021/6/21

#
try to test something : write something like this :
if(Greenfoot.getKey() != null)
    System.out.println(Greenfoot.getKey())
and then press the "k" key to see what it prints
Turbo_Thorsten Turbo_Thorsten

2021/6/21

#
I already tried that and it gave out k so I really don't know how this doesn't work.
danpost danpost

2021/6/21

#
Turbo_Thorsten wrote...
Your solution also only works with enter
Is your Caps-Lock on?
Turbo_Thorsten Turbo_Thorsten

2021/6/21

#
no
danpost danpost

2021/6/21

#
Turbo_Thorsten wrote...
no
Try:
System.out.println(""+automove);
to verify getting both true and false.
Super_Hippo Super_Hippo

2021/6/24

#
Turbo_Thorsten wrote...
Your solution also only works with enter
Maybe your k key is broken? The code works on my side.
danpost danpost

2021/6/24

#
Hippo's suggestion/code is best. Gbasire's last post breaks the "General advice" given by Hippo.
danpost danpost

2021/6/24

#
Super_Hippo wrote...
Maybe your k key is broken?
Try a different key, like "a" (for automove).
You need to login to post a reply.