Search Unity

AddForce jumps higher than it should (Bug) 2D

Discussion in 'Physics' started by Vaspix, Oct 2, 2019.

  1. Vaspix

    Vaspix

    Joined:
    Jun 8, 2019
    Posts:
    54
    Hi,
    I'm using this line to make my player jump but jumps always have different heights, and sometimes the player jumps around 3-4 times higher than it normally does.
    Code (CSharp):
    1. rb.AddForce(new Vector2(0, jSpeed * Time.deltaTime), ForceMode2D.Impulse);
    Did you ever have the same bug? How can I fix it? I'm just searching for any good jump script for a 2D game.
    Thank you!
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,481
    You're scaling the impulse by the time the last frame took (not sure why) so it's not surprising it's giving you different results each time. Also, don't apply this per-frame if you're running physics per-fixed-update as you'll potentially get a bunch of frames rendered and therefore the above called before a fixed-update happens.

    Either run your physics simulation per-frame (manual simulation) or add your forces during the fixed-update to ensure you only do the above once per simulation step.
     
    Joe-Censored and Vaspix like this.
  3. Vaspix

    Vaspix

    Joined:
    Jun 8, 2019
    Posts:
    54
    Ty for the respond.
    I actually found my mistake, I needed to call AddForce in FixedUpdate instead of Update, so it's all clear now!