Simple WASD key controls without "If" or rotation

Now this might seem weird, but maybe someone else needs a short camera snippet, which allows left, right, forward, backward, up and down… but no rotation. :mrgreen:


is_down = base.mouseWatcherNode.is_button_down
Camera = Vec3(0.0,1.0,5.0)
Keys = []

for k in ['d','a','c','v','s','w']:
    Keys.append(KeyboardButton.ascii_key(k))

for kk,k in enumerate(Keys):
    if is_down(k):
        kk2 = kk % 2
        v = ((kk2*-1) + (kk2 == 0))*0.1
        Camera[kk / 2] += v
        base.cam.setPos(Camera)

        break

The “*0.1” is there to reduce the stepsize, otherwise every keypress would move the camera a whole unit. That’s quite a lot in one step. Adjust it to your needs, like a fancy delta based on framerate or something.

This code works, because there’s three axis XYZ and three pairs of keys for each axis respectively. X is axis 0, controlled by d and a, which thus get the spot at the front of the Keys-array as the first pair of keys. You might notice already how this works.

X = 0 = d,a (d,a represent +1,-1 as d goes right (kk2==0, x+=1) and a goes left (kk2==1,x-=1))
Y = 1 = c,v
Z = 2 = w,s

Axis = position of key in array / 2
Which key of the pair is being pressed = modulo 2 of key’s position in array = 0…1
Convert to -1 or +1 = ((kk2*-1) + (kk2 == 0))

The best part is the last one!

kk2 can either be 0 or 1 == d or a == +1 or -1.
If (kk % 2 == 1), then (kk2*-1) must be -1, thus (kk2 == 0) must be False = -1 + 0 = -1 aka we move left.
If (kk % 2 == 0), then (kk2*-1) must be 0, thus (kk2 == 0) must be True = 0 + 1 = +1 aka we move right.

The same applies to every axis kk / 2, which has two keys kk % 2.

I hope you like it and some of you might want to use it. It beats a couple of Ifs. :slight_smile:

Thanks, i think i will use it :slight_smile: