iDevGames Forums

Full Version: Multiple Key Presses - Cocoa Events
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This may be a really simple fix, but I have no idea what I'm doing. I'm trying to use events (with keyDown and keyUp) to get user input, but I can't seem to get more than one key pressed registered at once. I have an array of bool values for each key so I can set the state of each key, but after looking all over the internet it doesn't even look like I can register multiple key presses with keyDown and keyUp. What is a simple way to register keyboard input for a game? Thanks!!
You're doing it right!

#import <Carbon/Carbon.h> // for kVK_* names

- (void)keyDown:(NSEvent *event)
    unsigned keyCode = [event keyCode];
    if (keyCode < 128) keysDown[keyCode] = YES;

- (void)keyUp:(NSEvent *event)
    unsigned keyCode = [event keyCode];
    if (keyCode < 128) keysDown[keyCode] = NO;

- (void)whereverYouUpdateTheStateOfYourGame
    if (keysDown[kVK_ANSI_A] && !keysDown[kVK_ANSI_D]) { /* move left */ }
    if (keysDown[kVK_ANSI_D] && !keysDown[kVK_ANSI_A]) { /* move right */ }
    if (keysDown[kVK_ANSI_W] && !keysDown[kVK_ANSI_S]) { /* move up */ }
    if (keysDown[kVK_ANSI_S] && !keysDown[kVK_ANSI_W]) { /* move down */ }

What are you doing wrong?

Be aware that not *every* set of simultaneous keys will work (hardware limitation).
Oh wow, I think I had my keyDown and keyUp functions all wrong. This is so much better, and now it's working! I was having this problem:

my code was very similar to that. Thanks for the help!
Reference URL's