You'll have to count and do the actual movement every couple of frames or so, otherwise the movement won't "lag" like you want it too. I stored the last pressed key in newKey on the keydown event and then every frame made the pastKey equivalent to the newKey so you can compare them before doing actions.
- Code: Select all
newKey = getLastKey();//last key pressed
Then I checked what keys were still held down whenever a key was released, and only if there was a combination where two opposing directions were not held would I change the newKey in order to have continuous movement without having to only press one key at a time.
- Code: Select all
char * key = GetKeyState();
if((key[KEY_RIGHT] ^ key[KEY_LEFT]) ^ (key[KEY_DOWN] ^ key[KEY_UP]))//keys in unopposed directions
{
if(key[KEY_UP])
newKey = KEY_UP;
else if(key[KEY_DOWN])
newKey = KEY_DOWN;
else if(key[KEY_LEFT])
newKey = KEY_LEFT;
else if(key[KEY_RIGHT])
newKey = KEY_RIGHT;
}
Then on the draw actor event, I checked if one of the movement keys was still being held and increased a timer (tick) by once every frame if the newKey and the pastKey were equal so we don't get sudden movement when switching directions and otherwise reset the variable to 0. Then if tick had "counted" 10 frames I would check the direction using newKey since it was our most recent direction and move that way.
- Code: Select all
char * key = GetKeyState();
moveing = (key[KEY_RIGHT] - key[KEY_LEFT]) || (key[KEY_DOWN] - key[KEY_UP]);// are we moving
tick = (newKey == pastKey && moveing) ? (tick+= 1):(tick = 0);//update tick
if(tick >= 10)//every 10 frames of moving in the same direction
{
switch(newKey)//find what direction and move there
{
case KEY_UP: y -= 16;
break;
case KEY_DOWN: y += 16;
break;
case KEY_LEFT: x -= 16;
break;
case KEY_RIGHT: x += 16;
break;
}
tick = 0;
}
pastKey = newKey;//pastKey updated
Demo attached of this working.
Working on a probably too ambitious project! Wild-west-adventure-RPG-shooter-thing.