views:

267

answers:

1

Hi, i usually develop for iPhone. But now trying to make a pong game in Cocoa desktop application. Working out pretty well, but i can't find a way to capture key events.

Here's my code:

#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

A: 

If your PongAppDelegate class doesn't inherent from NSResponder, it will not respond to a -keyDown event.

Even in a small app you want to use a controller subclass instead of dumping functionality in the app delegate.

TechZen
Do i use an viewcontroller or an windowcontroller. wich is the most usual?
Oscar
I would say the view controller. However, Cocoa is even more serious about the MVC design pattern and it assumes that most of the applications logic is in the data model. (See "represented object") In your case, this would mean that operations like `ballVelocity.x =- ballVelocity.x;` would ideally happen in the data model (a custom NSObject subclass). The view controller would only inform the model of the size of the display area and it would transfer information between the model and the view. Otherwise, it wouldn't do much.
TechZen