Search Unity

Custom Spring acceleration neverending increasing

Discussion in 'Physics' started by Risine, Jan 23, 2019.

  1. Risine

    Risine

    Joined:
    Dec 10, 2009
    Posts:
    154
    Hi everyone,
    I'm trying to make a simple spring algorithm between 2 objects, the formula is quite simple.
    But the acceleration and speed of my 2 objects don't stop increasing as if energy was constantly added.
    What's wrong with my approach?

    Code (CSharp):
    1. Spring = 0.5
    2. Damping = 1
    3. FixedDist = 2;
    4.  
    5. for each object in Update, I do :
    6.  
    7.            // Get Distance.
    8.            Vector3 delta = (this.transform.position - other.transform.position);
    9.            float distance = delta.magnitude;
    10.  
    11.            // Get Force.
    12.            Force = -Spring * (distance - FixedDist) * delta / distance - Damping * (this.Speed - other.Speed);
    13.  
    14. for each object in LateUpdate, I do :
    15.            Accel += Force / Mass;
    16.            Speed += Accel * Time.deltaTime;
    17.            transform.position += Speed * Time.deltaTime;
    18.  
     
  2. Risine

    Risine

    Joined:
    Dec 10, 2009
    Posts:
    154
    ok,
    I think I have my answer.
    I have to add some drag factor on accel and velocity at each update.