Created
May 24, 2021 19:17
-
-
Save keenanwoodall/951134976ad26a39e75b8b7643d026d6 to your computer and use it in GitHub Desktop.
C# implementation of Ming-Lun "Allen" Chou's springing functions for Unity (aka my favorite functions)
This file contains 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
// Source: http://allenchou.net/2015/04/game-math-precise-control-over-numeric-springing/ | |
public void Spring(ref float x, ref float v, float xt, float zeta, float omega, float h) | |
{ | |
float f = 1.0f + 2.0f * h * zeta * omega; | |
float oo = omega * omega; | |
float hoo = h * oo; | |
float hhoo = h * hoo; | |
float detInv = 1.0f / (f + hhoo); | |
float detX = f * x + h * v + hhoo * xt; | |
float detV = v + hoo * (xt - x); | |
x = detX * detInv; | |
v = detV * detInv; | |
} | |
public void Spring(ref Vector2 current, ref Vector2 velocity, Vector2 target, float dampingRatio, float angularFrequency, float timeStep) | |
{ | |
float f = 1.0f + 2.0f * timeStep * dampingRatio * angularFrequency; | |
float oo = angularFrequency * angularFrequency; | |
float hoo = timeStep * oo; | |
float hhoo = timeStep * hoo; | |
float detInv = 1.0f / (f + hhoo); | |
Vector2 detX = f * current + timeStep * velocity + hhoo * target; | |
Vector2 detV = velocity + hoo * (target - current); | |
current = detX * detInv; | |
velocity = detV * detInv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment