1

I am attempting to modify the controller file highway_overtake.py in order to access keyboard inputs from the user. After following the documentation, the relevant code appears as follows:

from Controller import Keyboard
keyboard = Keyboard();
keyboard.enable(50);
....
[other webots controller logic]
while driver.step () != -1
     key = keyboard.getKey( )
     if(key ==Keyboard.CONTROL+ord('M')):
          print 'Key Pressed'

I believe this is following the documentation verbatim, and have tried modifying the example with various different key inputs. How should I proceed?

Referenced Documentation: https://www.cyberbotics.com/doc/reference/keyboard

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    I just tried your code and it is working perfectly for me, the only minor issue is that `from Controller import Keyboard` should be replaced by `from controller import Keyboard`. Which version of Webots are you using? And on Which OS? have you tried printing `key`, if yes, what is the value? Note also that to be safe you should read the `keyboard.getKey()` value in a loop until it returns `-1` (if several keys are pressed it will return a different one each time until it has returned all of them and will then return `-1`). – David Mansolino Feb 24 '20 at 07:39
  • 2
    Please beware that you should first click in the 3D view of Webots, so that it's active and key press events are forwarded to your controller program. – Olivier Michel Feb 24 '20 at 08:45
  • Thought of improvement: Maybe it would make sense to forward keys automatically after "Play" is pressed ? (or just focus the 3D window) – Aerodynamic Feb 26 '20 at 15:33

1 Answers1

1

I don't know whats wrong with your code but, here is how you can take input from keyboard in webots:

from controller import Keyboard

timestep = int(robot.getBasicTimeStep())

keyboard=Keyboard()
keyboard.enable(timestep)

while robot.step(timestep) != -1:
    key=keyboard.getKey()
    if (key==Keyboard.CONTROL+ord('M')):
        print ('Ctrl+M is pressed')
#here you get print only when you press ctrl and m togather
#in webots ctrl + B is a shortcut which mess the window layouts thats why i changed B to M 
# hope it helps
Sachin Das
  • 319
  • 3
  • 8