- Home /
Rigidbody.AddForceAtPosition & functions
My first question has to do with function Update () and function FixedUpdate (). According to Unity docs, function FixedUpdate should be used when applying physics to rigidbodies. I have code that involves using rigidbody physics on a key press but it also includes other things such as changing values within the same if statement. Update is called before every frame is rendered. These values may change every frame. Can FixedUpdate be used for changing values every frame?
Also, what would be the result of putting rigidbody physics in Update?
My second questions about rigidbody.AddForceAtPosition. For adding a force on RaycastHit, I used this code:
hit.rigidbody.AddForceAtPosition (hit.transform.position, transform.position * hitForce);
Am I doing this right?
Answer by valyard · Nov 04, 2012 at 11:57 PM
First of all you should have split questions. But I'll try to answer both.
All physics calls you must do in FixedUpdate because that's where Unity recalculates everything physics related. You might not notice anything if calling physics methods in Update but usually behavior wil be wrong. If you see odd behavior check whether you have physics code in FixedUpdate.
And yes, you can set other parameters in FixedUpdate. But it runs with slower framerate than Update so parameters you update in FixedUpdate will not be seen immediately and their discreet values will span across several frames.
The second part. addForceAtPosition has the following signature: function AddForceAtPosition (force : Vector3, position : Vector3, mode : ForceMode = ForceMode.Force) : void. So you need to call it this way:
hit.rigidbody.AddForceAtPosition(force, hit.point);
Where force is the force you want to apply.
UPDATE
To execute specific code in Update and do something in FixedUpdate you could use a coroutine like this:
void Update() {
// your code
StartCoroutine(applyForce(hit, force));
}
IEnumerator applyForce(RaycastHit hit, Vector3 force) {
yield return new WaitForFixedUpdate();
hit.rigidbody.AddForceAtPosition(force, hit.point);
}
No appropriate version of 'UnityEngine.Rigidbody.AddForceAtPosition' for the argument list '(float, UnityEngine.Vector3)' was found.
Of course, because force must be a Vector3. Also I updated the post with coroutine example.
var hitForce : float;
hit.rigidbody.AddForceAtPostion (transform.TransformDirection (Vector3.forward) * hitForce, hit.point);
This should work as it has the Vector3, the force, and the point at which the ray hits the rigibody.
Your answer
Follow this Question
Related Questions
What's FixedUpdate 2 Answers
How do I fix jitter? 1 Answer
Rigidbody character and Update() function 1 Answer
Game not running properly on slow machines (low fps) 1 Answer
Is it okay to use ForceMode.VelocityChange in Update()? 1 Answer