gpt4 book ai didi

swift - 如何在 swift 中连接到外部游戏 Controller - apple tv

转载 作者:搜寻专家 更新时间:2023-10-30 21:58:42 24 4
gpt4 key购买 nike

我在这里遵循了本教程:https://cartoonsmart.com/how-to-support-external-game-controllers-with-swift-2-and-sprite-kit-for-the-new-apple-tv/将外部游戏 Controller 连接到 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。为了更加确定,我什至在应用程序商店的应用程序上测试了 Controller ,它运行良好。有人可以帮忙吗?

编辑:这是我的 didMove 函数:

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

最佳答案

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

无论如何,请确保您自己至少手动调用一次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:) 函数“发现” Controller ? (在 Game Controller Programming Guide 中描述:发现无线 Controller )

关于swift - 如何在 swift 中连接到外部游戏 Controller - apple tv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com