Triggering AddForce in Update()

If I’m not mistaken, AddForce should always be in FixedUpdate(). But say if this is triggered by a key/mouse press, what would be the best method for triggering it?

I was thinking something like this, but it doesn’t seem to work - I’m guessing because the force would only be added for once frame but then stopped when the bool is changed to false. I also don’t understand enough about how AddForce works.

bool ReadyToLaunch;

void Update()
if(Input.GetKeyDown(KeyCode.Space))
{
ReadyToLaunch = true;
}

void FixedUpdate()
{
if(ReadyToLaunch == true)
{
Rb.AddForce(Force, ForceMode.Impulse);
ReadyToLaunch = false;
}
}

This must be a very common requirement, is there a standard way of doing it?

Your approach is good, but you’ve forgotten to check if ReadyToLaunch is true in FixedUpdate.

Impulses are instant changes in the momentum, so it’s ok to add them once when triggered. If you want to apply a standard force for some frames then you may use Input.GetKey (instead of Input.GetKeyDown) within FixedUpdate.

Thanks for the reply Edy - yeah I’d left that line out by mistake. So this is a sound method otherwise?

Yes, it’s a correct method for detecting a GetKeyDown event with a reaction in FixedUpdate.

I know it’s been a really long while since you’ve posted this, but this was one of the issues I encountered as well. Although it is recommended that rb.AddForce() should always be in FixedUpdate(), ForceMode.Impulse should be an exception because it is done only once and you’re totally fine doing it in Update().

Please don’t necropost. The information you’re providing isn’t correct.

Calling things in FixedUpdate is often recommend but sometimes without understanding why and is often stated simply as “it’s because physics runs then” but that isn’t the core reason.

It’s not about where you call it but the effect any such call would have in relation to the frame-rate. Adding an impulse per-frame still means the impulse will scale with frame-rate which is the core issue and often not something desirable. Calling it during the FixedUpdate means you’ll get an impulse applied at a fixed-rate of (default) 50Hz and because when you add a force it’s added to a sum and that sum is time-integrated when the simulation runs, it means you’ll get the forces applied per-second.