Skip to content

Instantly share code, notes, and snippets.

@drZool
Created February 4, 2019 09:57
Show Gist options
  • Select an option

  • Save drZool/8ebcda5766eb321bfd837766ccbf1c26 to your computer and use it in GitHub Desktop.

Select an option

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)
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