- Home /
Script to calcualte the player's distance?
I need a script that says how far the player has travelled from an initial starting point, and to display that as a "score". Preferably javascript, I'm not comfortable with C++
C# not C++
@$$anonymous$$ryptos has the right answer for you.
Answer by Kryptos · Aug 23, 2012 at 01:26 PM
Just cumulate the delta distance between two updates.
// JS
var previousPosition : Vector3; // variable to keep the previous position
var cumulatedDistance : float;
function Awake()
{
// initialize to the current position
previousPosition = transform.position;
}
function Update()
{
// add the distance covered during the last frame
cumulatedDistance += (transform.position - previousPosition).magnitude;
// update the 'previous' position to the current one
previousPosition = transform.position;
}
C# version looks almost the same.
// C#
private Vector3 previousPosition; // variable to keep the previous position
public float cumulatedDistance;
void Awake()
{
// initialize to the current position
previousPosition = transform.position;
}
void Update()
{
// add the distance covered during the last frame
cumulatedDistance += (transform.position - previousPosition).magnitude;
// update the 'previous' position to the current one
previousPosition = transform.position;
}
This solution is very basic. You may need to check first if the distance covered isn't too small to prevent the distance value to jitter. For example:
// JS
var covered : float (transform.position - previousPOsition).magnitude;
if (covered < 0.001f)
{
// don't cumulate because the speed is less than 6 cm/s (at 60 FPS)
}
else
{
cumulatedDistance += covered;
}
Since calculating a distance uses a square root (a quite expensive calculation), it may be better to calculate it less often. You will loose some precision (the less frequent the less precision), but will save performance. For example you can use Start()
as a coroutine:
// C# (sorry I'm not familiar with coroutine in JS)
public float cumulatedDistance;
IEnumerator Start()
{
Vector3 previousPosition = transform.position;
this.cumulatedDistance = 0;
while (true)
{
// add the distance covered since the 'previous' position
this.cumulatedDistance += (transform.position - previousPosition).magnitude;
// update the 'previous' position to the current one
previousPosition = transform.position;
yield return new WaitForSeconds(1.0f);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613080050im_/https://answers.unity.com/themes/thub/images/avi.jpg)