At some point I will feel an irresistible urge to debunk the hairy mouse picking section of the Panda3D manual and, if at all possible, provide a *neat* API for detecting clicks on objects.
In the meantime, I did skim through the keyboard handling section, and it’s not as bad as it looks. Here’s a simple recipe for key handling:
1. Import DirectObject – a key handler must be a subclass of DirectObject.
2. Define a key handler class inheriting from DirectObject
3. Invoke accept(key,function) to bind a key to a callback function. This can be done in your constructor.
Here is how it looks:
#----------------------------------------------------
from direct.showbase.DirectObject import DirectObject
class KeyHandler(DirectObject):
# constructor
def __init__(self):
self.accept('arrow_left', self.lookLeft)
# handler
def lookLeft(self):
# this would rotate the camera to the left
base.camera.setH(base.camera,2)
#--------------------------------------------------
Useful key names (quote names, like ‘space’):
arrow_left/up/down/right f1,...,f12 escape,backspace,insert,home,... page_up/down enter [l/r]shift/control/alt (you can ommit l=left or r=right)
You can combine a modifier and a key, like ‘shift-a’, ‘control-shift-a’. Normally, you get the event on key press, if you want the key released event, you append -up, like ‘arrow_up-up’
.
If you’re trying to implement keys that perform an action continuously until released, it may be worth mentionning that this isn’t as simple as it looks. If you just try to detect the key-press, you’ll be getting only one key press until the key is released. You can detect repeat key presses by appending -repeat (e.g arrow_up-repeat). But that won’t solve the problem entirely because after pressing a key, there is a very noticeable delay before keyboard auto-repeat kicks in. I’m still looking into this one.
0 Responses to “Getting Into it: Handle Key Events using Panda3D”