Skip to content

Instantly share code, notes, and snippets.

@xSke
Created November 13, 2016 22:50
Show Gist options
  • Save xSke/ebeb60fb2dafacc3b07809743cd6f312 to your computer and use it in GitHub Desktop.
Save xSke/ebeb60fb2dafacc3b07809743cd6f312 to your computer and use it in GitHub Desktop.
Numerical Springing in Java/libgdx
import com.badlogic.gdx.math.MathUtils;
public class SpringingContext1D {
public float value;
public float target;
public float velocity;
public float damping;
public float frequency;
public SpringingContext1D(float damping, float frequency) {
this.damping = damping;
this.frequency = frequency;
}
public void update(float deltaTime) {
float angularFrequency = frequency;
angularFrequency *= MathUtils.PI2;
float f = 1.0f + 2.0f * deltaTime * damping * angularFrequency;
float oo = angularFrequency * angularFrequency;
float hoo = deltaTime * oo;
float hhoo = deltaTime * hoo;
float detInv = 1.0f / (f + hhoo);
float detX = f * value + deltaTime * velocity + hhoo * target;
float detV = velocity + hoo * (target - value);
value = detX * detInv;
velocity = detV * detInv;
}
}
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
public class SpringingContext2D {
public Vector2 value = new Vector2();
public Vector2 target = new Vector2();
public Vector2 velocity = new Vector2();
public float damping;
public float frequency;
public SpringingContext2D(float damping, float frequency) {
this.damping = damping;
this.frequency = frequency;
}
public void update(float deltaTime) {
float angularFrequency = frequency;
angularFrequency *= MathUtils.PI2;
float f = 1.0f + 2.0f * deltaTime * damping * angularFrequency;
float oo = angularFrequency * angularFrequency;
float hoo = deltaTime * oo;
float hhoo = deltaTime * hoo;
float detInv = 1.0f / (f + hhoo);
{
float detX = f * value.x + deltaTime * velocity.x + hhoo * target.x;
float detV = velocity.x + hoo * (target.x - value.x);
value.x = detX * detInv;
velocity.x = detV * detInv;
}
{
float detX = f * value.y + deltaTime * velocity.y + hhoo * target.y;
float detV = velocity.y + hoo * (target.y - value.y);
value.y = detX * detInv;
velocity.y = detV * detInv;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment