Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling input events in a MetalKit application

I created an application on OS X in Xcode using "Game" template that uses MetalKit. How do I handle input events like keyDown and keyUp? I tried adding

- (void)keyDown:(NSEvent *)theEvent
{
    NSLog( @"Key down\n" );
}

- (void)keyUp:(NSEvent *)theEvent
{
    NSLog( @"Key up\n" );
}

into AppDelegate and GameViewController but they are not called when I press a key.

like image 449
SurvivalMachine Avatar asked Sep 15 '25 04:09

SurvivalMachine


2 Answers

For Swift apps, add these to your MTKView subclass:

// yes, this MUST be here.
override var acceptsFirstResponder: Bool { 
    return true 
}
override func keyDown(with theEvent: NSEvent) {
    // do something 
}
override func keyUp(with theEvent: NSEvent) {
    // do something 
}
like image 122
Bobjt Avatar answered Sep 16 '25 22:09

Bobjt


If you are not using MetalKit, you would need to create a view that is a subclass of NSView and implement the following methods therein:

- (void)keyDown:(NSEvent *)theEvent
{
    NSLog(@"onKeyDown Detected; Merry Christmas, by the way.");
}

- (BOOL)acceptsFirstResponder
{
    return YES;
}

If you're using MetalKit, however, you would do the same and would implement the aforementioned methods in a view subclassing MTKView there instead.

I have tested on both versions; and keyDown was called when a key was pressed.

like image 21
Unheilig Avatar answered Sep 17 '25 00:09

Unheilig