GML how to continue moving my player even if left and right keys are being hold

F

footlegchicken

Guest
i want it so if i press right and my player goes right then i press left but still holding right i want my player to continue walking right.
same for left

this is my code
also i want sonic to stay in his right sprite if walking right

if keyboard_check(vk_right) {
x += 4;
sprite_index = spr_sdsonic_jog_right
image_speed = 0.3;
}

if keyboard_check(vk_left) {
x -= 4;
sprite_index = spr_sdsonic_jog_left
image_speed = 0.3;
}

if keyboard_check_released(vk_right) {
sprite_index = spr_sdsonic_idle_right
image_speed = 0.3;
}

if keyboard_check_released(vk_left) {
sprite_index = spr_sdsonic_idle_left
image_speed = 0.3;
}
 

TheouAegis

Member
You'll want to give keys priority status. I used an algorithm one time to give previously detected keys higher priority, but probably a simpler method would just be to use a ds_list to hold the keys in order.

Code:
///Create Event///
key_queue_h = ds_list_create();
key_queue_v = ds_list_create();
hkey = 0;
vkey = 0;
Code:
///Begin Step Event///
if keyboard_check_pressed(vk_right) ds_list_add(key_queue_h,vk_right);
if keyboard_check_pressed(vk_left) ds_list_add(key_queue_h,vk_left);
if keyboard_check_pressed(vk_up) ds_list_add(key_queue_v,vk_up);
if keyboard_check_pressed(vk_down) ds_list_add(key_queue_v,vk_down);

if keyboard_check_released(vk_right) ds_list_delete(key_queue_h, ds_list_find_index(key_queue_h,vk_right));
if keyboard_check_released(vk_left) ds_list_delete(key_queue_h, ds_list_find_index(key_queue_h,vk_left));
if keyboard_check_released(vk_up) ds_list_delete(key_queue_v,ds_list_find_index(key_queue_v,vk_up));
if keyboard_check_released(vk_down) ds_list_delete(key_queue_v,ds_list_find_index(key_queue_v,vk_down);

hkey = key_queue_h[|0];
vkey = key_queue_v[|0];
Then just use the values of hkey and vkey.


A similar method is to set a variable like hkey and vkey whenever one of the appropriate keys is held (not pressed). If the variable is currently 0, set the variable to the currently detected key, otherwise check if the key saved in the variable is still held and replace it if it isn't.
 
Top