- Home /
Rigidbody AddForce in Update
Can the Rigidbody.AddForce be added in a method called inside the Update() or does it have to be called in FixedUpdate()?
What are the consequence of calling it in a normal Update()?
Also, ive read there should not be a rigidbody inside a hierarchy of an object that itself has a rigidbody. Is this true? What happens if a rigidbody contains a rigidbody?
Answer by meat5000 · Nov 02, 2013 at 10:18 AM
Physics should be handled in FixedUpdate().
There are perhaps a few exceptions, like making a one off call to ForceMode.Impulse type AddForce or making a one-off velocity change.
The effect otherwise will be inaccurate physics and missed collisions.
So any check that could result in calling AddForce should not start in update but in fixedUpdate? Or i guess i could handle it like setting a flag so that it will be triggered next fixed update?
First statement is correct. Second statement will result in glitches and hangs unless you are very careful. Waiting for an Update() frame to finish before calling a routine in FixedUpdate is pretty much the same as calling the physics from Update(), you are introducing a time delay which will make physics simulation very uneven.
Update() frametime can vary wildly but FixedUpdate() executes with a Fixed time step.
Thank you. That is good information. I checked my code and i have an event that is being raised on a collision. And in the event handler it may result in an AddForce. So then its not handled in the FixedUpdate(). How should i do it?
If the AddForce is the result of OnCollisionEnter routine, handling it in that routine is just fine as it will only be called that one time and happens at the time, rather than having to wait for an unknown frametime.
Great thanks! I will make sure it is like that. Do you know of any reason we should not have objects with rigidbodies inside other objects with rigidbodies?
Answer by mkgame · Oct 01, 2017 at 11:02 AM
If you start a coroutine, which is waiting for FixedUpdate, then the force will be applied in the next FixedUpdate. I guess, this is what you looking for.
StartCoroutine( applyForceAtPosition(RootObjectRB, transform.up * RecoilForce, transform.position, ForceMode.VelocityChange) );
protected IEnumerator applyForceAtPosition(Rigidbody rb, Vector3 force, Vector3 pos, ForceMode forceMode) {
yield return new WaitForFixedUpdate();
rb.AddForceAtPosition(force, pos, forceMode);
yield break;
}
Your answer
Follow this Question
Related Questions
Setting Quaternion , are Euler angles updated in the same update function? 2 Answers
Unity Mouse Position Raycasting from Point 0 Answers
Issues using GetComponent 1 Answer
BCE0023 Error 1 Answer