Note that there are some explanatory texts on larger screens.

plurals
  1. PONo, really. What is the proper way to handle keyboard input in a game using Cocoa?
    text
    copied!<p>Let's say you're creating a game for Mac OS X. In fact, let's say you're creating Quake, only it's 2011 and you'd prefer to only use modern, non-deprecated frameworks.</p> <p>You want your game to be notified when the user presses (or releases) a key, <em>any key</em>, on the keyboard. This includes modifer keys, like shift and control. <strong>Edited to add:</strong> Also, you want to know if the left or right version of a modifier key was pressed.</p> <p>You also want your game to have a config screen, where the user can inspect and modify the keyboard config. It should contain things like:</p> <ul> <li>Move forward: W</li> <li>Jump: SPACE</li> <li>Fire: LCTRL</li> </ul> <p>What do you do? I've been trying to find a <em>good</em> answer to this for a day or so now, but haven't succeeded.</p> <p>This is what I've came up with:</p> <ul> <li>Subclass NSResponder, implement keyUp: and keyDown:, like in <a href="https://stackoverflow.com/questions/275088/how-do-i-collect-key-input-in-a-video-game-style-cocoa-app/275113">this answer</a>. A problem with this approach, is that keyUp: and keyDown: won't get called when the user presses only a modifier key. To work around that, you can implement flagsChanged:, but that feels like a hack.</li> <li>Use a <a href="http://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/c/func/CGEventTapCreate" rel="nofollow noreferrer">Quartz Event Tap</a>. This only works if the app runs as root, or the user has enabled access for assistive devices. Also, modifier key events still do not count as regular key events.</li> <li>Use the HIToolbox. There is virtually no mention at all of it in the 10.6 developer docs. It appears to be very, very deprecated.</li> </ul> <p>So, what's the proper way to do this? This really feels like a problem that should have a well-known, well-documented solution. It's not like games are incredibly niche.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload