- Home /
How to measure the overall distance travelled?
Hi, When my first level is complete I need a float that has measured how far my player has moved through out the level.
Problem is that I cant just use Vector3.Distance since its a top down game and my player can move freely back and forward on the x and z axis.
Is there any solution to this?
Thank you so much!
Answer by Hellium · Apr 16, 2018 at 01:47 PM
The total distance travelled by an entity is just the sum of the distances travelled each time the entity moves. For the sake of simplicity, you can compute the distance in the Update
MonoBehaviour function. However, keep in mind that Vector3.Distance
is "costly". If you have many entities, you should find a way to optimize the computation.
private Vector3 lastPosition ;
private float totalDistance ;
private void Start()
{
lastPosition = transform.position ;
}
private void Update()
{
float distance = Vector3.Distance( lastPosition, transform.position ) ;
totalDistance += distance ;
lastPosition = transform.position ;
}
private void OnDestroy()
{
Debug.Log("Total distance travelled:" + totalDistance ) ;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612160854im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
destroyed gameobject breaks variable detecting distance 1 Answer
Jumping Question 1 Answer
Animation doesn't play when distant check is triggered 1 Answer
Check distance between many objects 3 Answers
Check Between Enemy List 1 Answer