- Home /
Calculate the distance a object has moved.
Hi,
I'm trying to calculate the distance a object has moved to be able do decrease fuel (in a vehicle).
Or is best to calculate de overall time the object has been moving??
thanks
Answer by StephanK · Apr 27, 2010 at 06:30 AM
float distanceTravelled = 0; Vector3 lastPosition;
void Start() { lastPosition = transform.position; }
void Update() { distanceTravelled += Vector3.Distance(transform.position, lastPosition); lastPosition = transform.position; }
That works, but inicialy, it calculates de distance based on the inicial position of the object, and gives a wrong calculation.
any1 can convert it to javascript ^^
for the Vector3 lastPosition;
@John3D It is in "world units" like everything in Unity. It could be interpreted as meter, yes, but Unity itself doesn't have a unit for length.
Answer by v0nni · Jul 09, 2012 at 02:01 PM
Here is how i converted the entire code to javascript
private var distanceTravelled : float= 0; private var lastPosition:Vector3; function Start() { lastPosition = transform.position; } function Update() { distanceTravelled += Vector3.Distance(transform.position, lastPosition); lastPosition = transform.position; }
Answer by BawsAnimations · Sep 15, 2013 at 08:33 PM
Script Conversion to Javascript :
var DistanceTravelled : float = 0;
var lastPosition : Vector3;
function Start()
{
//cached data.
lastPosition = transform.position;
}
function Update()
{
DistanceTravelled += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;
}
Your answer
Follow this Question
Related Questions
Calculating player distance meter? C# Unity2D 1 Answer
How can I get the Time taken for the 2 moving objects to touch each other 2 Answers
Destroy instances after set time 1 Answer
Creating an equation to simulate time based on rate and distance. 0 Answers
Time a ball is thrown in the air? 2 Answers