WASD Optimization Nonsense
Last updated on
A friend and I work on hobby games every now and then. And for whatever silly reason we ended up ping pong’ing a useless optimization for our player navigation code.
Originally the code was several branches, that would add or subtract a vec3 if the key was pressed. After that the vec3 would be normalized and it could be used for navigation.
At some point one of use realized that both the branches and vector math were not required.
uint8_t kw = (keys[GAME_KEY_W] & GAME_KEY_DOWN) >> GAME_KEY_DOWN_BIT;
uint8_t ka = (keys[GAME_KEY_A] & GAME_KEY_DOWN) >> GAME_KEY_DOWN_BIT;
uint8_t ks = (keys[GAME_KEY_S] & GAME_KEY_DOWN) >> GAME_KEY_DOWN_BIT;
uint8_t kd = (keys[GAME_KEY_D] & GAME_KEY_DOWN) >> GAME_KEY_DOWN_BIT;
int8_t mx = kd - ka;
int8_t my = kw - ks;
uint8_t ml = (mx & my) & 1;
float len_rcp = (float[2]) { 1.0f, 0.70710678118f, } [ml];
move[0] = (float)mx * len_rcp;
move[1] = (float)my * len_rcp;
In a strange way while this code is more complicated, I find personally it has less mental overhead than previously.
Well we can now sleep knowing our navigation code doesn’t have branches or unrequired vector math.