- Home /
Setting a relative force for a rigid body
I am trying to create a harmonic engine script, meaning when ever I attach that script to a given gameObject it will start swinging in an harmonic motion,
So the problem is that as far as i can see unity only allow constant forces in rigidBody.AddForce so what i would like to do is change that force inside the FixedUpdate function
basically something like this will solve my problem
Start()
{
GetComponent<Rigidbody>().AddForce( ... some initial value of my force ...)
}
FixedUpdate()
{
GetComponent<Rigidbody>().ResetForce( ... current value of my force ...)
}
Answer by michaelb212 · Jul 13, 2015 at 09:31 AM
Going through the documentation and tutorials it turns out that FixedUpdate + ForceMode.Force is the right answer, meaning - The ForceMode.Force is designed to by used inside FixedUpdate to simulate a force that is changing with transform and time
As for the initial conditions when the GameObject is instantiated, The momentum can be set using ForceMode.Impulse.
In case of my harmonic engine it should look like this
void Start ()
{
GetComponent<Rigidbody>().AddForce(
Amplitude * AngularSpeed * Mathf.Cos(Phase),
0, 0, ForceMode.Impulse);
}
void FixedUpdate ()
{
GetComponent<Rigidbody>().AddForce(
- Mathf.Pow(AngularSpeed, 2) * Amplitude * Mathf.Sin(AngularSpeed * Time.time + Phase),
0, 0, ForceMode.Force);
}
Answer by Megolas · Jul 11, 2015 at 02:20 PM
You can use ForceMode: Rigidbody.AddForce(Vector3 force, ForceMode mode) and set forcemode to your liking - I think Impulse will work best for you.
Your answer