本文介绍了如何在视频游戏风格的Cocoa应用程序中收集键输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在黑客一个简单的Cocoa应用程序,使块像在视频游戏在屏幕上移动。我需要检测按键,但我不会有一个对话框的文本输入字段。

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.

推荐答案

在游戏视图中,定义keyUp和keyDown方法:

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

a href =http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html =nofollow noreferrer> NSView 和了解更多信息。请注意,keyDown和keyUp事件实际上是在,NSView的超类。

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.

这篇关于如何在视频游戏风格的Cocoa应用程序中收集键输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 14:43