- Home /
 
 
               Question by 
               eplaygame · Jul 26, 2021 at 06:16 PM · 
                physicsupdateaddforcefixedupdate  
              
 
              AddForce in Update
I want to add force during an animation clip (using OnStateUpdate which is the same as Update).
So, the question is: how to AddForce in the Update method properly as if it was the FixedUpdate?
               Comment
              
 
               
              It's the same as using FixedUpdate i think. I may be wrong but I've always done it the same way 
Answer by Eno-Khaon · Jul 26, 2021 at 11:29 PM
If you want to ensure that you're reliably applying your physics forces during FixedUpdate() while simultaneously basing it on an animation that plays during Update(), you could use a Queue<> (or List<>, on the same general basis). 
 
 In short, you add forces to be applied during the animation, then "play them back" during the next FixedUpdate().
 Queue<Vector3> qForces = new Queue<Vector3>();
 
 // Simplified example call
 void OnStateUpdate(/*etc.*/)
 {
     // etc.
     qForces.Enqueue([FORCE_TO_APPLY]);
     // etc.
 }
 void FixedUpdate()
 {
     if(qForces.Count > 0) // Only worry about this when the queue isn't empty
     {
         Vector3 combinedForce = Vector3.zero;
         while(qForces.Count > 0)
         {
             combinedForce += qForces.Dequeue();
         }
         // Make only a single Rigidbody.AddForce() call using the
         // sum of all forces gathered between physics passes
         rb.AddForce(combinedForce, ForceMode.[Impulse/VelocityChange/etc.]);
     }
 }
 
               Edit: Efficiency improvement
Your answer