Multiple Key Presses - Cocoa Events

Apprentice
Posts: 10
Joined: 2012.06
Post: #1
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!!
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #2
You're doing it right!

Code:
#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).
Quote this message in a reply
Apprentice
Posts: 10
Joined: 2012.06
Post: #3
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:

http://stackoverflow.com/questions/11515...cocoa-os-x

my code was very similar to that. Thanks for the help!
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Window focus events in Cocoa Jar445 2 5,425 Jan 18, 2009 06:02 PM
Last Post: Jar445
  Threaded events in Cocoa VolganPoet 6 5,514 May 11, 2005 05:24 PM
Last Post: Andrew