我的可可应用程序不会捕获关键事件

时间:2010-03-13 18:33:05

标签: objective-c cocoa keyboard

我通常为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

1 个答案:

答案 0 :(得分:1)

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

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