Search code examples
objective-cmacosinputmetalmetalkit

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.


Solution

  • 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.