My cocoa app won't capture key events

Posted by Oscar on Stack Overflow See other posts from Stack Overflow or by Oscar
Published on 2010-03-13T18:33:04Z Indexed on 2010/03/13 18:35 UTC
Read the original article Hit count: 273

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about cocoa

Related posts about keyboard