Need some GameKeys/KeyboardSensor Python help

I’ve been playing around with the GameKeys module and the keyboard sensor, with the goal of consolidating all of my KeySensor logic bricks into one. I’ve got a key list that returns any key that was JustPressed, Active, and Released.

Here’s my test file: http://www.christopherschons.com/temp/blender/gameKeysTest.blend

Question 1:
Is there a way to check if a list is empty? The currently.pressedKeys() should only be added to the list if there are list items.

Question 2:
I’ve sort of got it working, but the cube continues to move after key release. How would I make it move only if key is pressed or active?


import GameLogic as g
from GameKeys import *

cont = g.getCurrentController()
sensor = cont.getSensor("allKeys")
own= cont.getOwner()

move = cont.getActuator("movement")

if sensor.isPositive:
    keylist = cont.getSensor("allKeys").getPressedKeys() + cont.getSensor("allKeys").getCurrentlyPressedKeys()

print keylist


#movement variables

moveX=0
moveY=0
jump=0
speed=5


#NO_INPUTSTATUS = 0
#JUSTACTIVATED = 1
#ACTIVE = 2
#JUSTRELEASED = 3

for key in keylist:
    if key[1] == 1 or 2:
        if key[0] == UPARROWKEY:
            moveY = speed
        if key[0] == DOWNARROWKEY:
            moveY = -speed
        if key[0] == RIGHTARROWKEY:
            moveX = speed
        if key[0] == LEFTARROWKEY:
            moveX = -speed


#activate motion actuator

move.setLinearVelocity(moveX,moveY,jump,1)
g.addActiveActuator(move,1)


I expect there’s a command to check the length of an array, but I don’t know what it is off the top of my head. Try looking in the python documentation.

for Q2, try this


for key in keylist:
    if key[1] == 1 or 2:
        if key[0] == UPARROWKEY:
            moveY = speed
        if key[0] == DOWNARROWKEY:
            moveY = -speed
        else:
            moveY = 0
        if key[0] == RIGHTARROWKEY:
            moveX = speed
        if key[0] == LEFTARROWKEY:
            moveX = -speed
        else:
            moveX = 0

so if there’s no input, it sets the velocity to 0.

I dunno if this has been fixed in more recent versions, but as far as I’m aware, linear velocity cancels out all other forces (such as gravity) so there are issues with jumping/falling/etc.

Question one:

if len(list) != 0: # Replace list with your list name
# Function

Meaning if the Lenth (len) isn’t equal 0 (!= 0) the function can be processed.

I just found the answer in another thread. This method checks to see if keylist exist. Now the motion works fine.


if keylist:
   for key in keylist:
       etc.