Search Unity

Question Why are all my speed calculations wrong?

Discussion in 'Scripting' started by captainspaceman, Jan 11, 2022.

  1. captainspaceman

    captainspaceman

    Joined:
    Jul 14, 2017
    Posts:
    42
    I've tried a bunch of things but even when I do this:

    Code (CSharp):
    1.  
    2.  
    3.         float deltaTime = Time.deltaTime;
    4.         float dist = Vector3.Distance(lastPosition, transform.position);
    5.         lastPosition = transform.position;
    6.  
    7.         timer += deltaTime;
    8.         distAccumulator += dist;
    9.         if (timer >= 1)
    10.         {
    11.  
    12.             speedText.GetComponent<Text>().text = "mph " + (distAccumulator * 2.2369362920544025f).ToString();
    13.  
    14.             timer = 0;
    15.             distAccumulator = 0;
    16.         }
    it's wrong. That is a direct conversion from meters per second to MPH, I can't use it because I need to update the speed more frequently, but it is WAY off. When it reads 15 mph, it feels more like 2, and 100 mph feels more like 20. It's way off but I don't understand why, all my models and everything treat 1 Unity unit as 1 meter. It's even more off when I try dividing dist by deltaTime every frame and then multiplying by (1 / deltaTime) to get ms. This is in a FixedUpdate btw. Thank you.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    This code is just measuring distance. It is not measuring speed. if you want speed you have to do:

    Code (CSharp):
    1. float distanceInMeters = disAccumulator;
    2. float timeElapsed = timer;
    3.  
    4. float speedInMs = distanceInMeters / timeElapsed;
    5. float speedInMph = speedInMs * 2.23f; // whatever this number is
    Note you cannot avoid dividing by
    timeElapsed
    /
    timer
    because even though you're stopping after one second, Unity runs on discrete frames, so that if statement will run some time after 1 second has elapsed, for example 1.05 seconds or something.
     
  3. captainspaceman

    captainspaceman

    Joined:
    Jul 14, 2017
    Posts:
    42
    This was just to test some stuff, 0.05 seconds doesn't explain it being several orders of magnitude off and dividing it by the exact time instead of 1 actually makes the problem slightly worse.
     
  4. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,745
    Is it actually off, or does it feel off?

    Also:

    You should be using Time.fixedDeltaTime instead then.
     
  5. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,745
    Lurking-Ninja likes this.