如何连接到 swift 中的外部游戏控制器 - apple tv

How do I connect to a external game controller in swift - apple tv

我在这里遵循了这个教程:https://cartoonsmart.com/how-to-support-external-game-controllers-with-swift-2-and-sprite-kit-for-the-new-apple-tv/ 将外部游戏控制器连接到 sprite kit 中的 apple tv,但我无法使用教程代码完成此操作。我没有收到任何错误消息,但它根本无法正常工作。这是我的代码:

func setUpControllerObservers() {
    NotificationCenter.default.addObserver(self, selector: #selector(connectControllers), name: NSNotification.Name.GCControllerDidConnect, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(disconnectController), name: NSNotification.Name.GCControllerDidDisconnect, object: nil)
}

func connectControllers() {
    var count = 0
    for controller in GCController.controllers() {
        count = count + 1
        print(count)
        print(controller.extendedGamepad != nil)
        print(controller.microGamepad != nil)
        print(controller.gamepad != nil)
        if (controller.extendedGamepad != nil && controller.playerIndex == .indexUnset) {
            if (count == 1) {
                controller.playerIndex = .index1
            }
            else if (count == 2) {
                controller.playerIndex = .index2
            }
            else if (count == 3) {
                controller.playerIndex = .index3
            }
            else if (count == 4) {
                controller.playerIndex = .index4
            }
            controller.extendedGamepad?.valueChangedHandler = nil
            setupExtendedController(controller: controller)
        }
    }
}

func disconnectController() {

}

func setupExtendedController(controller: GCController) {
    controller.extendedGamepad?.valueChangedHandler = { (gamepad: GCExtendedGamepad, element: GCControllerElement) in
        // not calling
    }
}

调试时,我发现GCController.controllers()数组是空的,即使它连接到apple tv。为了更加确定,我什至在应用程序商店的应用程序上测试了控制器,它运行良好。有人可以帮忙吗?

编辑: 这是我的 didMove 函数:

didMove(to view: SKView) {
    setUpControllerObservers()
    connectControllers()
}

您的 setUpControllerObservers 函数何时以及从哪个 class 调用?我们需要更多背景信息来帮助您。

无论如何,请确保您自己至少手动调用一次 connectControllers 函数。您不能仅仅依靠传入通知来为您调用该函数。他们在您链接的教程中提到了这一点:

Notice too, we are calling connectControllers ourselves right after setUpControllerObservers. The first time the app runs, setUpControllerObservers will cause our NSNotification to also call connectControllers, but if we were to go back and forth between our GameScene and other class, we can’t rely on connectControllers getting called again from the notification. Which is why we call it ourselves.

您还应确保在您的应用完成启动之前不要调用这些函数(例如 AppDelegate 早期):

Call the controllers class method to retrieve an array of GCController objects for all connected controllers. [...] If there are no connected controllers or you call this method while your app is launching, the array will be empty.


编辑:

出于调试目的,您可以使用 startWirelessControllerDiscovery(completionHandler:) 函数尝试 'discovering' 控制器吗? (在 Game Controller Programming Guide:发现无线控制器中描述)