虚拟游戏控制器至少可以在运行 iOS 15 的任何视图控制器上运行,但出于工作目的,最好在横向查看,但您需要将代码作为物理游戏手柄完成。
要使虚拟游戏控制器出现,您需要注册一个物理游戏控制器,并在连接和断开控制器时应用通知功能,就像您使用物理控制器一样。
这是设置和注册我使用的虚拟和物理游戏控制器的代码,它对我有用。
第一个你需要导入游戏控制器库
import GameController
然后你在你的控制器类下定义虚拟控制器
class GameViewController: UIViewController {
// Virtual Onscreen Controller
private var _virtualController: Any?
@available(iOS 15.0, *)
public var virtualController: GCVirtualController? {
get { return self._virtualController as? GCVirtualController }
set { self._virtualController = newValue }
}
然后在 ViewDidLoad() 中调用 setupGameController 函数
override func viewDidLoad() {
super.viewDidLoad()
//your code
setupGameController()
}
这是设置虚拟和物理游戏控制器的主要功能
func setupGameController() {
NotificationCenter.default.addObserver(
self, selector: #selector(self.handleControllerDidConnect),
name: NSNotification.Name.GCControllerDidBecomeCurrent, object: nil)
NotificationCenter.default.addObserver(
self, selector: #selector(self.handleControllerDidDisconnect),
name: NSNotification.Name.GCControllerDidStopBeingCurrent, object: nil)
if #available(iOS 15.0, *)
{
let virtualConfiguration = GCVirtualController.Configuration()
virtualConfiguration.elements = [GCInputLeftThumbstick,
GCInputRightThumbstick,
GCInputButtonA,
GCInputButtonB]
virtualController = GCVirtualController(configuration: virtualConfiguration)
// Connect to the virtual controller if no physical controllers are available.
if GCController.controllers().isEmpty {
virtualController?.connect()
}
}
guard let controller = GCController.controllers().first else {
return
}
registerGameController(controller)
}
然后,要使用虚拟或物理游戏手柄操作,您需要将游戏控制器的连接和注册分配为
func handleControllerDidConnect(_ notification: Notification) {
guard let gameController = notification.object as? GCController else
{
return
}
unregisterGameController()
if #available(iOS 15.0, *)
{
if gameController != virtualController?.controller
{
virtualController?.disconnect()
}
}
registerGameController(gameController)
}
func handleControllerDidDisconnect(_ notification: Notification) {
unregisterGameController()
if #available(iOS 15.0, *) {
if GCController.controllers().isEmpty
{
virtualController?.connect()
}
}
}
func registerGameController(_ gameController: GCController) {
var buttonA: GCControllerButtonInput?
var buttonB: GCControllerButtonInput?
if let gamepad = gameController.extendedGamepad
{
buttonA = gamepad.buttonA
buttonB = gamepad.buttonB
}
buttonA?.valueChangedHandler = {(_ button: GCControllerButtonInput, _ value: Float, _ pressed: Bool) -> Void in
// Put here the codes to run when button A clicked
print("Button A Pressed")
}
buttonB?.valueChangedHandler = {(_ button: GCControllerButtonInput, _ value: Float, _ pressed: Bool) -> Void in
// Put here the codes to run when button B clicked
print("Button B Pressed")
}
}
func unregisterGameController()
{
}
这是一个非常基本的 Xcode 船舶样本的代码结果