Here's my simplified code:

import bge
from bge import logic

cont = logic.getCurrentController()
own = cont.owner
keyboard = bge.logic.keyboard
input_just_activated = bge.logic.KX_INPUT_JUST_ACTIVATED

primary_input_key = "SPACEKEY"
p = "bge.events." + primary_input_key

primary_input = keyboard.events[p]

if primary_input == input_just_activated:
    print("it worked!")

As the code suggests, I am trying to print "it worked!" into the console by keyboard input. It works when using keyboard.events[bge.events.SPACEKEY] as it is in its proper form, but when I change it to "bge.events." + primary_input_key it seems that it changes its form, making it no longer working. How can I have a string be converted to fit the game-engine's logic's keyboard input's form?



You are mixing separate things. This leads to confusion, quirky design and in best case it does not work (as it is not supposed to work together).

Some things you need to know about

Keyboard events

Keyboard events consists of two attributes:

  • The status (pressed, released ...) and
  • the involved key.

Keys are no strings. Keys are hardware. Keys are identified by key-codes. Key codes are numbers (not strings).

As nobody wants you to remember all the numbers there are some constants for better understanding e.g. bge.events.SPACEKEY which is key-code 32.

So the working code would be:

p = bge.events.SPACEKEY 
# which is
p = 32

I do not really understand what you are going to do. From what I see you try to create code from strings. This is possible. But not what you really want. Here you could do a "light" interpretation, by retrieving the attributes of a module:

getattr(bge.events, "SPACEKEY")

This can become handy when writing keyboard settings into a human readable file format.

Be Aware

The constants do not describe what is printed on the key. For example bge.events.YKEY is not necessarily the key with Y printed on. It describes the key-code (the number) of the key at that place.

To get the printed character on the key of your system you need to ask your OS. It can map the key-code to a string. This happens when you enter text anywhere - even in Blender.

The bad news

I have not found a way to map key-code to character through the OS keyboard mapping, neither with the BGE nor Python.

  • $\begingroup$ Thanks! I went with getattr(bge.events, "SPACEKEY") and it works perfectly! :) $\endgroup$
    – blackhole
    Dec 8 '15 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.