Hello there,
I'm trying to make a simple game in MATLAB, and I am using KeyPressFcn and KeyReleaseFcn callbacks to get player input from within a loop. It looks something like this:
boxfig=figure;drawnowakey='a';set(boxfig,'KeyPressFcn',{@Key_Down,akey},'KeyReleaseFcn',{@Key_Up,akey});lrshift=0;kk=1;while kk<2 drawnow fprintf([num2str(lrshift) '\n']);end %kk
function Key_Down(~,event,leftkey)if strcmp(event.Key,leftkey), assignin('base','lrshift',1); end endfunction Key_Up(~,event,leftkey)if strcmp(event.Key,leftkey), assignin('base','lrshift',0); end end
The code sets lrshift to 1 when the a-key is pressed, and to 0 when it's not pressed, and then prints the value of lrshift. However, the loop obviously runs faster than one can press and release a key, so it always records multiple subsequent key-presses. I would like the program to set lrshift to 1 once only when the key is first pressed, and then immediately back to 0 until the key has been released and is pressed again. At the moment, the output looks something like this:
00001 %<- a-key pressed
1111 0 %<- a-key released
001 %<- a-key pressed1111 0 %<- a-key released00
I would like it to look like:
00001 %<- a-key pressed00000 %<- a-key released0001 %<- a-key pressed00000 %<- a-key released00
I have tried to disable the callback to KeyPressFcn after the key is first pressed within the loop, but the result is still the same:
while kk<2 if lrshift==1 set(boxfig,'KeyPressFcn',[],'KeyReleaseFcn',{@Key_Up,akey}); else set(boxfig,'KeyPressFcn',{@Key_Down,akey},'KeyReleaseFcn',{@Key_Up,akey}); end drawnow fprintf([num2str(lrshift) '\n']);end %kk
Pausing for a short time is not an option since the game is still doing other things in the background.
I would be grateful if anyone could help me with this! Is KeyPressFcn even the right way to go about it?
Thank you 🙂
Best Answer