PDA

View Full Version : Cocoa Keyboard help


Iceman
2002.06.07, 09:00 PM
Hi,
I'm trying to get the arrow keys to work for my game, and it's not working. What am I doing wrong? Here's the code:

- (void)keyDown: (NSEvent *)theEvent {
NSString *keyChar = [theEvent characters];

if ( [keyChar isEqualToString:@""] ) {
//movement goes here
}

[self setNeedsDisplay:YES];
}

Thanks,
Iceman

Jeff Binder
2002.06.07, 10:56 PM
Try something like this:


- (void)keyDownNSEvent *)theEvent {
NSString *keyChars = [theEvent characters];
int index;

for (index = 0; index < [keyChars length]; index++) {
if ([keyChars characterAtIndex:index] == NSUpArrowFunctionKey) {
//movement goes here
}

//...
}

[self setNeedsDisplay:YES];
}

Iceman
2002.06.08, 05:45 PM
Thanks I like the feel of using arrow keys much better on my game :) .

Iceman

AlainODea
2005.08.01, 09:52 PM
To get a multiple-keys down keyboard interaction coded in Cocoa you can see an article I posted called GameKeyboardHandling on the Cocoa Dev wiki:
http://www.cocoadev.com/index.pl?GameKeyboardHandling

Josh
2005.08.01, 10:00 PM
Again, we appreciate the link but this thread is 3 years old. :)

nabobnick
2005.08.01, 10:06 PM
You can also do this:

BOOL upArrow = NO;
BOOL downArrow = NO;

-(void)keyDown: (NSEvent *)theEvent {
NSString *keyChar = [theEvent characters];

if ( [keyChars characterAtIndex:index] == NSUpArrowFunctionKey ) {
upArrow = YES;
}
}

-(void)keyUp: (NSEvent *)theEvent {
NSString *keyChar = [theEvent characters];

if ( [keyChars characterAtIndex:index] == NSUpArrowFunctionKey ) {
upArrow = NO;
}
}

// Function called from timer or polling loop
-(void)gameMain {
if (upArrow) {
//Move up
}

if (downArrow) {
//Move down
}

[self setNeedsDisplay:YES];
}


EDIT: It's good info have (sorry about the old post).