/game-porting-skills:using-game-controllerfrom game-porting-skills
Guides developers on using Apple's GameController framework (GCController) for game controller input on Apple platforms, including porting from Windows APIs (XInput, DirectInput, RawInput).
Ships in game-porting-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A comprehensive guide to Apple's GameController framework - covering Swift/ObjC APIs, platform considerations, and porting from Windows.
Use the GameController framework when writing code for Apple platforms that interacts with game controllers. The GCController API presents a common abstraction over gamepad and joystick input devices. The GameController framework supports popular game controllers including the Sony DualSHOCK 4, Sony DualSense, Nintendo Switch Pro, and Microsoft Xbox controllers. Advanced features available on these controllers - IMU, Rumble, and Adaptive Triggers (force feedback) - are supported.
When porting Windows code that calls RawInput (e.g, RegisterRawInputDevices) or HID (HidP_*) APIs to interfce with Sony, Nintendo, and other non-Xbox controllers, AVOID writing equivalent code that uses IOKit and IOHIDManager APIs. PREFER to re-write the code to use the abstractions provided by the GCController API instead.
GCController represents a connected gamepad or joystick device. You obtain the currently connected devices from GCController.controllers, listen for new connections (GCControllerDidConnectNotification) and disconnections (GCControllerDidDisconnectNotification), and monitor for input from the one(s) you are interested in.GCController object.
GCControllerLiveInput object returned from the GCController.input property (modern API), or through the GCPhysicalInputProfile (or subclass thereof) object returned from GCController.physicalInputProfile (older profile based API).GCMotion object returned from the GCController.motion property. If this property returns nil, the controller does not feature an integrated IMU and does not produce motion input.CHHapticEngine created from the GCDeviceHaptics object returned from GCController.haptics property. If this property returns nil, the controller does not feature integrated haptic or rumble actuators.GCControllerLiveInput or GCPhysicalInputProfile. A GCController may represent a device with elements beyond those found on an Xbox controller.| Topic | Description | See |
| Getting Started | Discovering controllers; controller lifecycle. | This file, "Controller Lifecycle" |
| Inspecting the Controller Device | Checking device compatibility, and representing the device in your UI. | reference/inspect-the-device.md |
| Element names | How elements (buttons, stick, triggers) are identified on a controller. | reference/input-element-names.md |
| Modern input | Receiving input (buttons, stick, triggers) via callbacks, or reading input from a polling loop. Supporting input from any controller. | reference/modern-input.md |
| Profile-based input | Receiving input from controllers that support one of several Apple-defined profiles. | reference/profile-based-input.md |
| Haptics / rumble | Play haptic patterns and rumble effects to a controller. | reference/haptics.md |
| Platform notes | Platform best practices and quirks (macOS vs iOS vs tvOS vs visionOS) | reference/platform-notes.md |
The following is a list of important APIs in the GameController framework, and where you can learn more about them.
# Devices (This file, "Controller Lifecycle")
<GCDevice> https://developer.apple.com/documentation/gamecontroller/gcdevice
GCController https://developer.apple.com/documentation/gamecontroller/gccontroller
# Modern Physical Input (`reference/modern-input.md`)
<GCDevicePhysicalInputState> https://developer.apple.com/documentation/gamecontroller/gcdevicephysicalinputstate
<GCDevicePhysicalInput> https://developer.apple.com/documentation/gamecontroller/gcdevicephysicalinput
<GCDevicePhysicalInputStateDiff> https://developer.apple.com/documentation/gamecontroller/gcdevicephysicalinputstatediff
<GCPhysicalInputSource> https://developer.apple.com/documentation/gamecontroller/gcphysicalinputsource
<GCPhysicalInputExtents> https://developer.apple.com/documentation/gamecontroller/gcphysicalinputextents
<GCPhysicalInputElementCollection> https://developer.apple.com/documentation/gamecontroller/gcphysicalinputelementcollection-c.class?language=objc
<GCPhysicalInputElement> https://developer.apple.com/documentation/gamecontroller/gcphysicalinputelement
<GCButtonElement> https://developer.apple.com/documentation/gamecontroller/gcbuttonelement
<GCAxisElement> https://developer.apple.com/documentation/gamecontroller/gcaxiselement
<GCSwitchElement> https://developer.apple.com/documentation/gamecontroller/gcswitchelement
<GCDirectionPadElement> https://developer.apple.com/documentation/gamecontroller/gcdirectionpadelement
<GCLinearInput> https://developer.apple.com/documentation/gamecontroller/gclinearinput
<GCAxisInput> https://developer.apple.com/documentation/gamecontroller/gcaxisinput
<GCAxis2DInput> https://developer.apple.com/documentation/gamecontroller/gcaxis2dinput
<GCRelativeInput> https://developer.apple.com/documentation/gamecontroller/gcrelativeinput
<GCPressedStateInput> https://developer.apple.com/documentation/gamecontroller/gcpressedstateinput
<GCTouchedStateInput> https://developer.apple.com/documentation/gamecontroller/gctouchedstateinput
<GCSwitchPositionInput> https://developer.apple.com/documentation/gamecontroller/gcswitchpositioninput
GCControllerInputState https://developer.apple.com/documentation/gamecontroller/gccontrollerinputstate
GCControllerLiveInput https://developer.apple.com/documentation/gamecontroller/gccontrollerliveinput
# Profile-based Physical Input (`reference/profile-based-input.md`)
GCPhysicalInputProfile https://developer.apple.com/documentation/gamecontroller/gcphysicalinputprofile
GCMicroGamepad https://developer.apple.com/documentation/gamecontroller/gcmicrogamepad
GCDirectionalGamepad https://developer.apple.com/documentation/gamecontroller/gcdirectionalgamepad
GCGamepad https://developer.apple.com/documentation/gamecontroller/gcgamepad
GCExtendedGamepad https://developer.apple.com/documentation/gamecontroller/gcextendedgamepad
GCXboxGamepad https://developer.apple.com/documentation/gamecontroller/gcxboxgamepad
GCDualShockGamepad https://developer.apple.com/documentation/gamecontroller/gcdualshockgamepad
GCDualSenseGamepad https://developer.apple.com/documentation/gamecontroller/gcdualsensegamepad
GCControllerElement (aliased to GCDeviceElement) https://developer.apple.com/documentation/gamecontroller/gccontrollerelement
GCControllerButtonInput (aliased to GCDeviceButtonInput) https://developer.apple.com/documentation/gamecontroller/gccontrollerbuttoninput
GCControllerAxisInput (aliased to GCDeviceAxisInput) https://developer.apple.com/documentation/gamecontroller/gccontrolleraxisinput
GCControllerDirectionPad (aliased to GCDeviceDirectionPad) https://developer.apple.com/documentation/gamecontroller/gccontrollerdirectionpad
GCControllerTouchpad (aliased to GCDeviceTouchpad) https://developer.apple.com/documentation/gamecontroller/gccontrollertouchpad
GCDualSenseAdaptiveTrigger https://developer.apple.com/documentation/gamecontroller/gcdualsenseadaptivetrigger
The GameController framework is part of the macOS, iOS, tvOS, and visionOS SDKs.
#import <GameController/GameController.h>
or
@import GameController
import GameController
When writing new code or modernizing existing code, follow these current best practices.
Ensure the following key is present in the application's Information Property List (Info.plist):
<key>GCSupportsControllerUserInteraction</key>
<true/>
This key with a true value tells the system that the application supports game controller input.
When writing new code or modernizing existing code, look for these anti-patterns and suggest a resolution.
The product category returned from GCController.productCategory is intended to help your application display appropriate artwork for the controller only.
nullable (optional) properties return a non-nil value, based on a prior product category check. if controller.productCategory == GCProductCategoryDualSense {
// WRONG: Do NOT assume controller supports the DualSense profile
// because productCategory is GCProductCategoryDualSense.
let dualSenseGamepad = controller.extendedGamepad as! GCDualSenseGamepad
let adaptiveLeftTrigger: GCDualSenseAdaptiveTrigger = dualSenseGamepad.leftTrigger
// WRONG: Do NOT assume controller has adaptive trigger because the
// productCategory is GCProductCategoryDualSense.
let adaptiveRightTrigger = controller.physicalInputProfile.buttons[GCInputRightTrigger] as! GCDualSenseAdaptiveTrigger
}
if controller.productCategory == GCProductCategoryDualShock4 || controller.productCategory == GCProductCategoryDualSense {
// WRONG: Do NOT assume controller supports motion input because the
// productCategory identifies a PlayStation controller
let motion = controller.motion!
motion.sensorsActive = true
// WRONG: Do NOT assume controller supports haptics because the
// productCategory identifies a PlayStation controller
let haptics = controller.haptics!
// WRONG: Do NOT assume a haptics locality is available because the
// productCategory identifies a PlayStation controller.
let hapticsEngine = haptics.createEngine(withLocality: .leftHandle)!
}
Instead, check for controller features and inputs individually.
// CORRECT: Check if `controller.extendedGamepad` is a `GCDualSenseGamepad`.
if let dualSenseGamepad = controller.extendedGamepad as? GCDualSenseGamepad {
let adaptiveLeftTrigger: GCDualSenseAdaptiveTrigger = dualSenseGamepad.leftTrigger
}
else if let extendedGamepad = controller.extendedGamepad {
// Handle non-DualSense extended gamepad
let leftTrigger: GCControllerButtonInput = extendedGamepad.leftTrigger
}
else {
// Notify the player their controller is not compatible with the game.
}
// CORRECT: Check if controller supports motion input (has an IMU)
if let motion = controller.motion {
motion.sensorsActive = true
}
// CORRECT: Check if controller supports haptics
if let haptics = controller.haptics {
// CORRECT: Handle failure if `GCHapticsLocalityLeftHandle` is not
// available.
if let hapticsEngine = haptics.createEngine(withLocality: .leftHandle) {
}
// Fallback to defaut locality.
else if let hapticsEngine = haptics.createEngine(withLocality: .default) {
}
else {
// GCHapticsLocalityDefault is guaranteed to be supported, but
// errors can occur creating the haptics engine.
}
}
Apple operating systems allow users to remap game controllers controls in system settings. You should NOT offer a UI for remapping controls in your application.
The framework posts a GCControllerDidConnectNotification when a controller becomes available to your application (typically when the device connects to the host), and a GCControllerDidDisconnectNotification when a controller becomes unavailable (device disconnects from the host). The GCController.controllers array reflects the currently avaiable controllers. Do not make assumptions about the ordering of this array.
/// Assume this object manages game controller input sources within your
/// application or engine.
class GameControllerInputManager: NSObject
{
override init() {
super.init()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(controllerDidConnect(_:)), name: .GCControllerDidConnect, object: nil)
notificationCenter.addObserver(self, selector: #selector(controllerDidDisconnect(_:)), name: .GCControllerDidDisconnect, object: nil)
// Handle controllers that are already connected when app launches.
for controller in GCController.controllers() {
handleConnection(controller)
}
}
deinit {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: .GCControllerDidConnect, object: nil)
notificationCenter.removeObserver(self, name: .GCControllerDidDisconnect, object: nil)
}
// Controller connected
@objc func controllerDidConnect(_ notification: Notification) {
if let controller = notification.object as? GCController {
self.handleConnection(controller)
}
}
// Controller disconnected
@objc func controllerDidDisconnect(_ notification: Notification) {
if let controller = notification.object as? GCController {
self.handleDisconnection(controller)
}
}
}
Calls to +[GCController startWirelessControllerDiscoveryWithCompletionHandler:] are not necessary and should be removed. Users pair wireless game controllers in the system Bluetooth settings.
The framework keeps track of the "current controller". This is the device that most recently connected, or that input was most recently received from. Single-player games should use the current controller as their input source.
/// Assume this object manages game controller input sources within your
/// application or engine.
class GameControllerInputManager: NSObject
{
// OPTION 1: Listen for notifications when the current controller changes.
// Implement this option, if your application prefers to register
// callbacks on the `GCController` to receive input.
override init() {
super.init()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(controllerDidBecomeCurrent(_:)), name: .GCControllerDidBecomeCurrent, object: nil)
notificationCenter.addObserver(self, selector: #selector(controllerDidStopBeingCurrent(_:)), name: .GCControllerDidStopBeingCurrent, object: nil)
}
deinit {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: .GCControllerDidBecomeCurrent, object: nil)
notificationCenter.removeObserver(self, name: .GCControllerDidStopBeingCurrent, object: nil)
}
@objc func controllerDidBecomeCurrent(_ notification: Notification) {
if let controller = notification.object as? GCController {
self.becomeCurrent(controller)
}
}
@objc func controllerDidStopBeingCurrent(_ notification: Notification) {
if let controller = notification.object as? GCController {
self.resignCurrent(controller)
}
}
func becomeCurrent(_ controller: GCController) {
// Register callbacks on the new current controller.
}
func resignCurrent(_ controller: GCController) {
// Unregister callbacks on the previous current controller
}
// OPTION 2: When polling controller input during your game loop, read
// from the current controller. Implement this option if your
// application prefers to poll for input.
// Assume this function is called during each iteration ("tick") of your
// game loop.
func handleInput() {
// NOTE: Accessing the current controller is an atomic operation.
if let currentController = GCController.current {
// Read input from the current controller
let aButtonPressed = currentController.physicalInputProfile.buttons[GCInputButtonA]?.isPressed ?? false
let leftTriggerPressed = currentController.physicalInputProfile.buttons[GCInputLeftTrigger]?.isPressed ?? false
let leftTriggerValue: Float = currentController.physicalInputProfile.buttons[GCInputLeftTrigger]?.value ?? .zero
let leftThumbstickX = currentController.physicalInputProfile.dpads[GCInputLeftThumbstick]?.xAxis.value ?? .zero
let leftThumbstickY = currentController.physicalInputProfile.dpads[GCInputLeftThumbstick]?.yAxis.value ?? .zero
// Handle input...
}
}
For multiplayer games, set controller.playerIndex to map each controller to a player slot. This also controls the player indicator LEDs on supported controllers (e.g, DualSense, Xbox Wireless):
/// Assume this object manages game controller input sources within your
/// application or engine.
class GameControllerInputManager: NSObject
{
var playerControllers: InlineArray<4, GCController?>
func nextAvailablePlayerIndex() -> Int? {
for i in playerControllers.indices {
if playerControllers[i] == nil {
return i
}
}
return nil
}
func handleConnection(_ controller: GCController) {
if let playerIndex = nextAvailablePlayerIndex() {
self.playerControllers[playerIndex] = controller
// NOTE: In C/C++/Objective-C, check if playerIndex is less than
// (<) GCControllerPlayerIndex4
if let gcPlayerIndex = GCControllerPlayerIndex(rawValue: playerIndex) {
controller.playerIndex = gcPlayerIndex
}
}
...
}
func handleDisconnection(_ controller: GCController) {
controller.playerIndex = .indexUnset
// Remove controller from the playerControllers array
...
}
}
For single player games, avoid modifying the playerIndex.
IMPORTANT: AVOID using the playerIndex value as an index into an array, or key into a collection. The playerIndex is shared state - it can be modified by other clients, and therefore may change unexpectedly. If you need to associate app-specific data to a GCController object, use the Objective-C runtime's associated objects feature.
A GCController instance represents the lifetime of a single device connection. When the same device disconnects and later reconnects, a new GCController instance is created.
When a device connects, the framework takes the following actions on the main thread (main dispatch queue):
GCController to the GCController.controllers array.GCControllerDidStopBeingCurrentNotification notification with the current GCController (skipped if there is no current controller).GCController to the GCController.current property.GCControllerDidBecomeCurrentNotification with the new GCController.GCControllerDidConnectNotification with the new GCController.When a device disconnects, the framework takes the following actions on the main thread (main dispatch queue):
GCController from the GCController.controllers array.GCControllerDidStopBeingCurrentNotification notification with the disconnected GCController.GCController.current property.GCControllerDidBecomeCurrentNotification with the new current GCController.GCControllerDidDisconnectNotification with the disconnected GCController.When input is received from a device, the framework makes the device the current GCController:
GCControllerDidStopBeingCurrentNotification notification with the previous current GCController (skipped if there is no current controller).GCController to the GCController.current property.GCControllerDidBecomeCurrentNotification with the new current GCController.tvOS and visionOS require additional setup to receive game controller input using the GameController framework; discussed in reference/platform-notes.md.
The GameController framework has offered profile-based APIs for accessing and monitoring game controller physical input since its inception. Recent OS versions added modern physical input APIs, supporting fast snapshots and atomic polling.
Prefer to use the modern physical input APIs (reference/modern-input.md) unless:
GCVirtualController or TCTouchController to display on-screen touch controls on iOS.Otherwise, use the profile-based physical input APIs (reference/profile-based-input.md).
If you are updating a codebase that is already using the GameController framework to interface with game controllers, look for usages of these outdated APIs or patterns and suggest to modernize them.
Look for existing code using the following deprecated APIs:
GCMicroGamepadSnapshotDataFromNSData
NSDataFromGCMicroGamepadSnapshotData
GCMicroGamepadSnapShotDataV100FromNSData
NSDataFromGCMicroGamepadSnapShotDataV100
GCGamepadSnapShotDataV100FromNSData
NSDataFromGCGamepadSnapShotDataV100
GCExtendedGamepadSnapshotDataFromNSData
NSDataFromGCExtendedGamepadSnapshotData
GCExtendedGamepadSnapShotDataV100FromNSData
NSDataFromGCExtendedGamepadSnapShotDataV100
Update to use snapshot techniques discussed in reference/modern-input.md or reference/profile-based-input.md.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub apple/game-porting-toolkit --plugin game-porting-skills24 skills in this plugin
/compiling-with-metal-shaderconverterALWAYS use when compiling DXIL/HLSL to metallib with Metal shader converter (commonly referred to as MSC) via the metal-shaderconverter CLI or libmetalirconverter (IRCompiler, IRObject, IRShaderReflection) at runtime. Covers offline/runtime DXIL compilation, root signatures, reflection output, ray tracing shaders, geometry/tessellation emulation compilation, framebuffer fetch in HLSL, programmable blending in HLSL, Metal_HLSL.inc, and compatibility flags. Do NOT trigger for binding compiled shaders to encoders — use integrating-metal-shaderconverter-shaders for that./creating-metal4-shader-pipelinesALWAYS use when creating Metal pipeline state objects with Metal 4 descriptors (MTL4RenderPipelineDescriptor, MTL4ComputePipelineDescriptor, MTL4MeshRenderPipelineDescriptor) via MTL4Compiler. Covers function descriptors, function constant specialization, flexible/unspecialized PSOs, color-attachment mapping, async compilation (MTL4CompilerTask), pipeline caching (MTL4Archive, MTL4PipelineDataSetSerializer), static/binary shader linking, and pipeline reflection. Do NOT trigger for HLSL/DXIL → metallib — use compiling-with-metal-shaderconverter./debugging-rendering-issuesALWAYS use when a user porting a game to Metal reports a rendering issue — blank screen, wrong output, or anything that looks incorrect on Metal vs. the source platform. Covers black screen, missing geometry, wrong colors, gamma/sRGB problems, texture artifacts, z-fighting, alpha blending, flickering, visual corruption, and upside-down/mirrored geometry. Works with or without a GPU trace. Do NOT trigger when the user just wants to inspect an existing .gputrace./integrating-metal-shaderconverter-shadersALWAYS use when integrating Metal shader converter (commonly referred to as MSC) shaders at runtime — binding model, top-level argument buffer (TLAB), root signature resource locations, descriptor/sampler heaps, static samplers, bindless resources, vertex fetch, separate stage-in, geometry/tessellation emulation, compute dispatch, unbounded arrays, and append/consume buffers. Do NOT trigger for compiling DXIL/HLSL to metallib — use compiling-with-metal-shaderconverter for that./managing-metal4-resourcesALWAYS use when working with Metal 4 resources — buffer / texture / heap creation, storage modes, `MTLResidencySet` management, heap aliasing, purgeable state, texture view pools, GPU lossless compression, and deferred destruction. Trigger for MTLBuffer, MTLTexture, MTLHeap, MTLResidencySet, addAllocation, requestResidency, useResidencySet, addResidencySet, MTLStorageMode*, MTLPurgeableState, MTLTextureViewPool, MTLResourceViewPool, newTextureViewWithPixelFormat:, copyFromBuffer:toTexture:, "GPU fault on resource", "non-resident resource", heap aliasing. Do NOT trigger for TBDR architecture or Metal 3 → Metal 4 namespace tables — use `translating-to-metal4-api`. Barrier visibility / `MTL4VisibilityOption*` / render-pass transition barriers — use `managing-metal4-synchronization`. `CAMetalLayer.residencySet` — use `presenting-metal-drawables`. `NS::SharedPtr` / autorelease pool / ARC bridging — use `managing-metal-cpp-lifetimes`./managing-metal4-synchronizationMetal 4 explicit synchronization — barriers, fences, events, and cross-API state translation (from D3D12, Vulkan, OpenGL). Use when porting GPU synchronization, translating resource state transitions, or debugging barrier-related visual corruption.Other plugins' skills for the same job