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)ap开发者_JAVA百科plicationDidFinishLaunching:(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
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.
精彩评论