Page 1 of 1

Handle simultaneous keys pressed

Posted: Tue Feb 20, 2018 1:29 pm
by Clyde
Hi there!

My son and I want to create a little car racing game. If I press the "arrow up" key the car should drive "forwards" and if LEFT oder RIGHT is pressed (simultaneously) the car should rotate accordingly. So I tried this:

Code: Select all

...

Function rotateCar(direction)
	DebugPrint("rotateCar")
EndFunction

Function moveTrack(speed)
	DebugPrint("moveTrack")
EndFunction

Function p_HandlerFunc(msg)
  
  Switch(msg.action)
  	Case "OnKeyDown":
	    If msg.key = "LEFT" Then rotateCar("left")
	    If msg.key = "RIGHT" Then rotateCar("right")
	    If msg.key = "UP" Then moveTrack(1)
	    If msg.key = "DOWN" Then moveTrack(-1)
    EndSwitch
EndFunction

Repeat
    WaitEvent
Forever
The car (to be more precise: the track) moves correctly when I press UP oder DOWN (moveTrack() is called). When I hold UP/DOWN key and additionally press LEFT or RIGHT this new key press is not recognized, which means just moveTrack() is called but not rotateCar() additionally.

What is the best way to this situation?

Thanks in advance!

Re: Handle simultaneous keys pressed

Posted: Wed Feb 21, 2018 7:50 pm
by airsoftsoftwair
Which platform are you on? On Windows it's the other way around: Holding down UP and then LEFT results in the UP events getting lost.

Re: Handle simultaneous keys pressed

Posted: Wed Feb 21, 2018 10:20 pm
by Clyde
I am on Windows. Sorry if I mixed it up, as I didn't have the compiled program here when I wrote the post.

Either way it is not good in my situation if any event gets lost. :-)

Re: Handle simultaneous keys pressed

Posted: Sat Feb 24, 2018 9:09 pm
by airsoftsoftwair
I'm afraid that's the way keys are handled by Windows. You can see this in other applications as well. Just open Notepad and hold down "a". Then hold down "b" while "a" is still down. You'll see that now only "b" is added to the text even though "a" is still down.

Still, you can solve your problem by internally keeping track of which keys are down. When you get "OnRawKeyDown" set the flag, on "OnRawKeyUp" clear the flag. Then it should work fine.

Also keep in mind that most keyboards won't be able to deal with more than two keys that are down at the same time because of hardware limitations. Related reading: Keyboards Are Evil

Re: Handle simultaneous keys pressed

Posted: Sat Feb 24, 2018 10:30 pm
by Clyde
Ok, I see the point, thanks a lot!

Yeah, I thought about setting flags, too, as a workaround. Thanks for the hint. I will try that and also try to implement using a joyad.

Thanks!