Search Unity

Mileage

Discussion in 'Scripting' started by Fekzh21, Mar 22, 2019.

  1. Fekzh21

    Fekzh21

    Joined:
    Dec 29, 2018
    Posts:
    18
    How could I create a kind of mileage that tells me how far I've traveled?
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    How are you moving your object - using physics API's or by translating positions yourself?

    What do you mean by "how far I've travelled" - As the crow flies from an origin point or ground covered?
     
  3. Fekzh21

    Fekzh21

    Joined:
    Dec 29, 2018
    Posts:
    18
    I am using this code to be able to know the distance between the player and where he has to arrive. What I want to achieve now is some counter that tells me how much distance the player has traveled from the total meters.


    Code (CSharp):
    1. DISTANCIAtesoro = Vector3.Distance(Tesoro.position, transform.position);
     
  4. mbaske

    mbaske

    Joined:
    Dec 31, 2017
    Posts:
    473
    You could create a queue of waypoints. Periodically store your object's position in the queue.
    Then you can either get the distance travelled between position 0 (first) and position N (last). Or sum up all the individual segments: distance(pos0, pos1) + distance(pos1, pos2) + ... + distance(posN-1, posN) to get the total distance travelled.
     
  5. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    I'm not sure exactly what you want. Given you have shown a calculation for "how far from where I am to my target position", It would seem there are 2 remaining possibilities :
    1. You want the straight-line distance between where you started from and where you are now (regardless of the route taken to get here).
    2. You want the distance that has been travelled since you started.
    So for (1), it will be similar to what you already have:
    Vector3.Distance(start.position, transform.position)


    For (2), you could use
    myMileage += mySpeed * Time.deltaTime
    if you are doing the calculation inside
    Update()
    (this would not work properly if used within
    FixedUpdate()
    ).
     
  6. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You can every Update get the distance between your current position and your previously saved position and add that to a float or double, then save your current position as your previous position for use in the next Update. The float or double will be your "mileage." If using physics movement you might do this in FixedUpdate instead. If the performance hit is too much you could experiment with reducing the frequency of this, but the more you reduce the frequency the more inaccurate the result will be.

    Could do the same thing using a coroutine instead of Update/FixedUpdate.