不完全是。在使用Cocoa的游戏中处理键盘输入的正确方法是什么? [英] No, really. What is the proper way to handle keyboard input in a game using Cocoa?

查看:94
本文介绍了不完全是。在使用Cocoa的游戏中处理键盘输入的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设您正在为Mac OS X创建一个游戏。事实上,假设您正在创建Quake,只有2011年,您更愿意使用现代的,非过时的框架。

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.

您希望当用户在键盘上按下(或释放)键(任何键)时通知您的游戏。这包括调制键,如移位和控制。 已编辑要添加:此外,您想知道是否按下了修改键的左侧或右侧版本。

You want your game to be notified when the user presses (or releases) a key, any key, on the keyboard. This includes modifer keys, like shift and control. Edited to add: Also, you want to know if the left or right version of a modifier key was pressed.

有一个配置屏幕,其中用户可以检查和修改键盘配置。应包含以下内容:

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:


  • 前进:W

  • 跳转:SPACE

  • 火:LCTRL

你做什么?我一直在尝试找到一个好的答案一天左右,但未成功。

What do you do? I've been trying to find a good answer to this for a day or so now, but haven't succeeded.

这是什么我想出了:


  • 子类NSResponder,实现keyUp:和keyDown :,就像此答案。这种方法的一个问题是,当用户只按下一个修饰键时,keyUp:和keyDown:不会被调用。

  • 使用 Quartz事件点击。这只有在应用程序作为根用户运行或用户已启用对辅助设备的访问时才有效。此外,修饰键事件仍不会计为常规键事件。

  • 使用HIToolbox。在10.6开发者文档中几乎没有提到它。

  • Subclass NSResponder, implement keyUp: and keyDown:, like in this answer. 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.
  • Use a Quartz Event Tap. 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.
  • 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.

那么,什么是正确的方法呢?这真的感觉像一个问题,应该有一个众所周知,有充分证据的解决方案。

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.

推荐答案

像其他人说的,使用没有什么问题 - flagsChanged:。还有另一个选项:使用IOKit HID API。你应该使用这反过来的操纵杆/游戏手柄输入,以及可争辩的鼠标输入;它可能或可能不方便键盘输入,取决于你在做什么。

As others have said, there’s nothing wrong with using -flagsChanged:. There is another option: use the IOKit HID API. You should be using this anyway for joystick/gamepad input, and arguably mouse input; it may or may not be convenient for keyboard input too, depending on what you’re doing.

这篇关于不完全是。在使用Cocoa的游戏中处理键盘输入的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆