【问题标题】:My cocoa app won't capture key events我的可可应用程序不会捕获关键事件
【发布时间】:2011-01-27 05:23:42
【问题描述】:

我通常为 iPhone 开发。但现在尝试在 Cocoa 桌面应用程序中制作乒乓球游戏。工作得很好,但我找不到捕捉关键事件的方法。

这是我的代码:

#import "PongAppDelegate.h"

#define GameStateRunning 1
#define GameStatePause 2

#define BallSpeedX 10
#define BallSpeedY 15

@implementation PongAppDelegate

@synthesize window, leftPaddle, rightPaddle, ball;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    gameState = GameStateRunning;
    ballVelocity = CGPointMake(BallSpeedX, BallSpeedY);
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES];
}


- (void)gameLoop {
    if(gameState == GameStateRunning) {
        [ball setFrameOrigin:CGPointMake(ball.frame.origin.x + ballVelocity.x, ball.frame.origin.y + ballVelocity.y)];

        if(ball.frame.origin.x + 15 > window.frame.size.width || ball.frame.origin.x < 0) {
            ballVelocity.x =- ballVelocity.x;
        }

        if(ball.frame.origin.y + 35 > window.frame.size.height || ball.frame.origin.y < 0) {
            ballVelocity.y =- ballVelocity.y;
        }
    }
}


- (void)keyDown:(NSEvent *)theEvent {
    NSLog(@"habba");
    // Arrow keys are associated with the numeric keypad
    if ([theEvent modifierFlags] & NSNumericPadKeyMask) {
        [window interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
    } else {
        [window keyDown:theEvent];
    }
}

- (void)dealloc {
    [ball release];
    [rightPaddle release];
    [leftPaddle release];
    [super dealloc];
 }

@end

【问题讨论】:

    标签: objective-c cocoa keyboard


    【解决方案1】:

    如果您的 PongAppDelegate 类不是 NSResponder 固有的,它不会响应 -keyDown 事件。

    即使在小型应用程序中,您也希望使用控制器子类而不是在应用程序委托中转储功能。

    【讨论】:

    • 我使用视图控制器还是窗口控制器。哪个是最常见的?
    • 我会说视图控制器。然而,Cocoa 对 MVC 设计模式更加认真,它假设大多数应用程序逻辑都在数据模型中。 (请参阅“表示的对象”)在您的情况下,这意味着像 ballVelocity.x =- ballVelocity.x; 这样的操作理想地发生在数据模型(自定义 NSObject 子类)中。视图控制器只会通知模型显示区域的大小,它会在模型​​和视图之间传递信息。否则,它不会做太多。
    猜你喜欢
    • 2018-09-04
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多