Is this how multiple keys are typically handled?

Member
Posts: 321
Joined: 2004.10
Post: #1
I thought I'd see a ton of examples, but I've been googling and
so far have only find single key examples. Is this "optimal"?
I would like to introduce Option key + Up Arrow and that would
mean an even bigger boolean conditional?

if ( keystate[SDLK_LCTRL] && keystate[SDLK_UP] ) // Ctrl + Up Arrow
{
blah, blah, blah
}
if ( keystate[SDLK_UP] && !keystate[SDLK_LCTRL]) // Up Arrow only
{
blah, blah, blah
}
Quote this message in a reply
Member
Posts: 72
Joined: 2006.10
Post: #2
Well, yes and no. Performance-wise it won't change anything. Those checks count for zilch compared to the rest of stuff your program does (remember, always profile before you optimize).

On the other hand, if you care about your general coding pratices, there is indeed a lot of room for improvement here. Analyze what is checked in wich order, you are checking twice for the same criteria, and the other criteria is checked for both itself and its inverse.
Quote this message in a reply
Member
Posts: 111
Joined: 2002.06
Post: #3
SDL has key modifier definitions for keys like Shift, Control, and Option. The modifiers have the KMOD prefix instead of SDLK.

SDL programs usually check for each key individually when handling multiple keys. Suppose you want to use the arrow keys to move the player and pressing two arrow keys moves the player diagonally. If the player presses both the left and up arrow keys, the player moves up and left. What you would do is check if the player pressed the up arrow key, check if the player pressed the left arrow key, then move the player based on what keys were pressed.

Code:
Boolean movedUp;
Boolean movedLeft;

// Check for keypresses
if (keystate[SDLK_UP])
    movedUp = true;

if (keyState[SDLK_LEFT])
    movedLeft = true;

// Move based on what keys were pressed
if ((movedUp) && (movedLeft))
    MoveUpAndLeft();
else if (movedUp)
    MoveUp();
else if (movedLeft)
    MoveLeft();
I typed the code off the type of my head so the C syntax may not be perfect, but you should get the idea of what to do.

Mark Szymczyk
http://www.meandmark.com
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Using GLUT With Multitouch and Command Keys Rasterman 7 4,565 Feb 10, 2010 07:40 PM
Last Post: Rasterman
  GLUT using modifier keys alone n00bprogrammer 7 5,850 Dec 26, 2004 02:06 AM
Last Post: FCCovett