Created
January 27, 2022 01:56
-
-
Save schwa/4b90a8fdb9f4d55951233daa954c66ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func movement() async { | |
// TODO: Dont use async version because it hangs! | |
GCController.startWirelessControllerDiscovery { } | |
while !Task.isCancelled { | |
// Wait for any controller to become current | |
_ = await NotificationCenter.default.notifications(named: .GCControllerDidBecomeCurrent, object: nil).makeAsyncIterator().next() | |
guard let currentController = GCController.current, let gamepad = currentController.extendedGamepad else { | |
return | |
} | |
// Start a task to print all game pad events | |
let eventsTask = Task { | |
for await element in gamepad.events { | |
print(element) | |
} | |
} | |
// Wait for that device to stop being current | |
_ = await NotificationCenter.default.notifications(named: .GCControllerDidStopBeingCurrent, object: currentController).makeAsyncIterator().next() | |
// Kill the current task | |
eventsTask.cancel() | |
} | |
GCController.stopWirelessControllerDiscovery() | |
} | |
extension GCExtendedGamepad { | |
enum Event { | |
case elementChanged(GCDeviceElement) | |
} | |
var events: AsyncStream <Event> { | |
AsyncStream<Event> { continuation in | |
valueChangedHandler = { _, element in | |
continuation.yield(.elementChanged(element)) | |
} | |
continuation.onTermination = { @Sendable [weak self] _ in | |
self?.valueChangedHandler = nil | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment