Skip to content

Instantly share code, notes, and snippets.

@RomanEsin
Last active June 28, 2020 09:34
Show Gist options
  • Save RomanEsin/968c1bb76235f8002bd254296d486a64 to your computer and use it in GitHub Desktop.
Save RomanEsin/968c1bb76235f8002bd254296d486a64 to your computer and use it in GitHub Desktop.
Animate Game Controller light. This little code snippet will allow you to animate the light of the controller when using GameController API.

GameController Light Animations

This will help you animate the DualShock 4 controller's light color as seen in this session.

Quick start

  1. Create a file in your project called ControllerAnimatable.swift and paste the code from below into it.
  2. Make your ViewController adopt the ControllerAnimatable protocol
  3. Add controller variable which will return the current GCController, you are responsible for handling, Example: var controller: GCController { GCController.current! }. Note that if you already have stored controller property just return it in the controller's getter, like here var controller: GCConotroller { myController }.

Usage

Call animate(to:duration:completion:) to animate the controller's light color.

import Foundation
import GameController
protocol ControllerAnimatable: class {
var controller: GCController { get }
}
extension ControllerAnimatable {
/// Animates controller light color to a specified color of `GCColor` type.
/// - Parameters:
/// - color: Defines what color the animation will resolve to.
/// - duration: Duration of the animation.
/// - completion: **Closure** Called upon animation completion.
func animate(to color: GCColor, duration: TimeInterval, _ completion: (() -> ())? = nil) {
let queue = OperationQueue()
let currentColor = controller.light!.color
// The difference between the color to animate to and the current color.
let diff = (color.red - currentColor.red, color.green - currentColor.green, color.blue - currentColor.blue)
let steps = Int(duration * 20)
// Iterates through each colors and interpolates them.
for i in 0..<steps {
// Schedule the color update
queue.schedule(after: .init(Date() + Double(i) * duration / Double(steps))) { [weak self] in
guard let self = self else { return }
self.controller.light?.color = GCColor(red: currentColor.red + Float(i) * diff.0 / Float(steps),
green: currentColor.green + Float(i) * diff.1 / Float(steps),
blue: currentColor.blue + Float(i) * diff.2 / Float(steps))
}
}
}
}
@chih98
Copy link

chih98 commented Jun 27, 2020

Awesome snippet! Excited to see how this progresses

@RomanEsin
Copy link
Author

@RomanEsin
Copy link
Author

Adopted OperationQueue @ revision 7 as suggested by @chih98

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment