Created
February 4, 2019 09:57
-
-
Save drZool/8ebcda5766eb321bfd837766ccbf1c26 to your computer and use it in GitHub Desktop.
Semi framerate independent 2d spring&damp function. (Not fully framerate independent since the target position isn't updated)
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
| using UnityEngine; | |
| using System.Collections; | |
| public class SpringVector2 | |
| { | |
| public Vector2 target; | |
| public Vector2 current; | |
| public Vector2 velocity; | |
| public float spring = 100f; | |
| public float damp = 20f; | |
| float rest; | |
| public SpringVector2 () | |
| { | |
| } | |
| public SpringVector2 (float spring, float damp) | |
| { | |
| this.spring = spring; | |
| this.damp = damp; | |
| } | |
| public Vector2 Update (float deltaTime) | |
| { | |
| const float step = 0.001f; //16 times every frame when playing in 60fps | |
| deltaTime += rest; | |
| while (deltaTime > step) { | |
| deltaTime -= step; | |
| var distanceVector = target - current; | |
| velocity += spring * distanceVector * step; | |
| velocity *= 1 - (damp * step); | |
| current += velocity * step; | |
| } | |
| rest = deltaTime; | |
| return current; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment