Skip to content

Instantly share code, notes, and snippets.

@devindazzle
Created August 23, 2016 12:07
Show Gist options
  • Save devindazzle/61ba4a1c3b5852188925472d698b8187 to your computer and use it in GitHub Desktop.
Save devindazzle/61ba4a1c3b5852188925472d698b8187 to your computer and use it in GitHub Desktop.
The smoothDamp function in Unity implemented using Swift
/**
* Gradually changes a value towards a desired goal over time - implemented from Unity C#
*/
public func smoothDamp(current c: CGFloat, target t: CGFloat, currentVelocity: inout CGFloat, smoothTime time: CGFloat, maxSpeed: CGFloat = CGFloat.infinity, deltaTime: CGFloat) -> CGFloat {
let smoothTime = max(0.0001, time)
let num = 2 / smoothTime
let num2 = num * deltaTime
let num3 = 1 / (1 + num2 + 0.48 * num2 * num2 + 0.235 * num2 * num2 * num2)
var num4 = c - t
let num5 = t
let num6 = maxSpeed * smoothTime
num4 = min(max(num4, -num6), num6)
let target = c - num4
let num7 = (currentVelocity + num * num4) * deltaTime
currentVelocity = (currentVelocity - num * num7) * num3
var num8 = target + (num4 + num7) * num3
if (num5 - c > 0) == (num8 > num5) {
num8 = num5
currentVelocity = (num8 - num5) / deltaTime
}
return num8
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment