Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

objective c - How do I collect key input in a video-game style Cocoa app?

I'm hacking on a simple Cocoa app to make blocks move around the screen like a video game. I need to detect key presses, but I'm not going to have text entry fields like a dialog box would have.

How do I get key presses without text controls? In particular, I need to get arrow keys.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your game view, define the keyUp and keyDown methods:

@interface MyView : NSView
-(void)keyUp:(NSEvent*)event;
-(void)keyDown:(NSEvent*)event;
@end

@implementation MyView

-(void)keyUp:(NSEvent*)event
{
    NSLog(@"Key released: %@", event);
}

-(void)keyDown:(NSEvent*)event
{   
    // I added these based on the addition to your question :)
    switch( [event keyCode] ) {
        case 126:   // up arrow
        case 125:   // down arrow
        case 124:   // right arrow
        case 123:   // left arrow
            NSLog(@"Arrow key pressed!");
            break;
        default:
            NSLog(@"Key pressed: %@", event);
            break;
    }
}
@end

See the documentation for NSView and NSEvent for more info. Note that the keyDown and keyUp events are actually defined on NSResponder, the super class for NSView.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...