Skip to content

Instantly share code, notes, and snippets.

@cdfisher
Last active November 18, 2025 22:29
Show Gist options
  • Select an option

  • Save cdfisher/4ffaa4d182b25c2f4d3bce04689cdb72 to your computer and use it in GitHub Desktop.

Select an option

Save cdfisher/4ffaa4d182b25c2f4d3bce04689cdb72 to your computer and use it in GitHub Desktop.
Spring animation for Unity
using UnityEngine;
public class Spring : MonoBehaviour
{
GameObject A, B;
Vector3 posA, posB;
Vector3 FS, FD, Gravity, NetForce, Accel, V;
int Mass = 1;
int KS = 5;
int LR = 2;
int KD = 1;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
A = GameObject.Find("BoxA");
B = GameObject.Find("BoxB");
posA = A.transform.position;
posB = B.transform.position;
V = new Vector3(0, 0, 0);
}
Vector3 SpringForce()
{
posA = A.transform.position;
posB = B.transform.position;
Vector3 springForce = -KS * (new Vector3(posA.x - posB.x, posA.y - posB.y, posA.z - posB.z).magnitude - LR) * ((posA - posB) / ((posA - posB).magnitude));
return springForce;
}
Vector3 DampingForce()
{
Vector3 dampingForce = -KD * V;
return dampingForce;
}
// Update is called once per frame
void Update()
{
// Calculate spring force Fs on A
FS = SpringForce();
// Calculate damping force Fd
FD = DampingForce();
// Calculate gravity force Fg on A
Gravity = Mass * new Vector3(0, -2.5F, 0);
NetForce = FS + FD + Gravity;
Accel = NetForce / Mass;
V = V + (Accel * Time.deltaTime);
posA = posA + (V * Time.deltaTime);
A.transform.position = posA;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment