GameControllerKit

Hello everyone!

I've created a package to make it easier to interact with gamecontrollers in Swift.

Features:

  • Maps buttons automatically.
  • Support for DualSense, DualShock, and Xbox controllers.
  • Change the LED on a playstation controller.
  • Support for Paddle buttons

Documentation

https://0xwdg.github.io/GameControllerKit/documentation/gamecontrollerkit/

Sample usage

import SwiftUI
import GameControllerKit

struct ContentView: View {
    /// The game controller kit
    @State
    var gameController = GameControllerKit()

    /// Log
    @State
    var log: [String] = []

    var body: some View {
        VStack {
            Button {
                gameController.set(color: .GCKRandom)
            } label: {
                Text("Random Color")
            }

            Text("Controller: \(gameController.controller?.productCategory ?? "None"), " +
                 "\((gameController.controllerType ?? .generic).description)")
            Text("Last action:\n\(String(describing: gameController.lastAction)).")

            GCKControllerView()
                .environmentObject(gameController)

            List {
                ForEach(log.reversed(), id: \.self) { text in
                    Text(text)
                }
            }
        }
        .padding()
        .onAppear {
            gameController.set(handler: handler)
            UIApplication.shared.isIdleTimerDisabled = true
        }
    }

    /// Handler
    ///
    /// - Parameters:
    ///   - action: action
    ///   - pressed: is the button pressed?
    ///   - controller: which controller?
    public func handler(
        action: GCKAction,
        pressed: Bool,
        controller: GCKController
    ) {
        log.append(
            "\(String(describing: action))(\(action.position.arrowRepresentation)) \(pressed ? "Pressed" : "Unpressed"), " +
            "Controller #id \(String(describing: controller.playerIndex.rawValue))"
        )

        if action == .buttonA && pressed {
            // set to a random color
            gameController.set(color: .GCKRandom)
        }
    }
}

Screenshots

iOS

MacOS

tvOS

6 Likes