# Calculate the distance a object has moved.

 0 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 more ▼ asked Apr 27 '10 at 06:24 AM Narven 49 ● 2 ● 3 ● 10 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 ``````float distanceTravelled = 0; Vector3 lastPosition; void Start() { lastPosition = transform.position; } void Update() { distanceTravelled += Vector3.Distance(transform.position, lastPosition); lastPosition = transform.position; } `````` more ▼ answered Apr 27 '10 at 06:30 AM StephanK 6k ● 39 ● 53 ● 93 That works, but inicialy, it calculates de distance based on the inicial position of the object, and gives a wrong calculation. Apr 27 '10 at 06:59 AM Narven Based on my respawn... is giving already 160 Apr 27 '10 at 07:00 AM Narven I edited the code... Apr 27 '10 at 06:01 PM StephanK thx! it works perfectly. Apr 20 '11 at 05:57 AM iker any1 can convert it to javascript ^^ for the Vector3 lastPosition; Feb 02 '12 at 09:55 AM wenhua add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users
 0 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; }` more ▼ answered Jul 09 '12 at 02:01 PM v0nni 16 ● 1 ● 3 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email: