Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Ballistics script not giving consistent results

Discussion in 'Scripting' started by Yocal, Nov 17, 2017.

  1. Yocal

    Yocal

    Joined:
    Feb 10, 2014
    Posts:
    22
    I tried this script but it's causing me some trouble with consistency:

    - https://forum.unity.com/threads/free-bullet-ballistics-script-pejsa-method.418325/

    I send the projectile flying by using:

    Code (CSharp):
    1. rb.AddForce (transform.forward * (float)muzzelVelmps, ForceMode.Impulse);
    This seems to work perfectly. But if I shoot 10 projectiles, they hit 10 different places. They are very consistent in the direction they take, but the distance they travel varies quite a bit. In 14km it can easily be +/- 300m.

    Any idea what could cause this? I don't see anything that could cause the calculations to end up with different results...

    // Yoc.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    The step-by-step numerical integration of the physics engine can easily cause a bit of variation. 300m out of 14 km isn't all that much (about 2%).

    If you need better precision than that, then I think you'll need to eschew the physics engine and move the projectile yourself, along a pre-computed path (i.e., no stepwise integration where errors can accumulate).
     
  3. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
    The numerical integration would normally be an issue but the code uses a fixed update (like Unity physics) so the results should be consistent each time. If you want to post the project I'd be willing to have a look and see if I can spot any obvious issues.
     
  4. Yocal

    Yocal

    Joined:
    Feb 10, 2014
    Posts:
    22
  5. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
    I had a look and it seems to be the bit of code that you're firing the projectile from that's causing the problem. It's running in the 'update' loop and the physics runs in 'fixedupdate' so you'll get slightly different results because of the timing difference.

    If you change the Controller.cs->Update to FixedUpdate they should all land in the same place. If you're doing a physics game it's probably best to do all your game logic in FixedUpdate too so that it matches up with the physics (also means it'll work the same way on slow/fast PCs and on mobile devices).
     
  6. Yocal

    Yocal

    Joined:
    Feb 10, 2014
    Posts:
    22
    Wow, so I actually fixed my problem by typing 'Fixed' in my code. I think that's a first...

    It worked ;-) Thanks ton!

    // Yoc.
     
    tonemcbride likes this.