2010-03-13 46 views
0

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

如果您PongAppDelegate類從NSResponder類沒有固有的,它不會給-keyDown事件作出響應。

即使在一個小應用程序中,您希望使用控制器子類而不是應用程序委託中的轉儲功能。

+0

我是否使用viewcontroller或windowcontroller。這是最常見的? – Oscar 2010-03-14 08:51:05

+0

我會說視圖控制器。然而,Cocoa對於MVC設計模式更加認真,並且假定大部分應用程序邏輯都在數據模型中。 (請參閱「表示的對象」)對於您的情況,這意味着像'ballVelocity.x = - ballVelocity.x;'這樣的操作理想情況下會發生在數據模型(一個自定義的NSObject子類)中。視圖控制器只會通知模型顯示區域的大小,它會在模型​​和視圖之間傳遞信息。否則,它不會做太多。 – TechZen 2010-03-14 13:36:46

相關問題