A Unity ID allows you to buy and/or subscribe to Unity products and services, shop in the Asset Store and participate
in the Unity community.
Discussion in 'Scripting' started by Fekzh21, Mar 22, 2019.
How could I create a kind of mileage that tells me how far I've traveled?
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?
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.
DISTANCIAtesoro = Vector3.Distance(Tesoro.position, transform.position);
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.
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 :
You want the straight-line distance between where you started from and where you are now (regardless of the route taken to get here).
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()).
myMileage += mySpeed * Time.deltaTime
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.