x


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

more ▼

asked Apr 27 '10 at 06:24 AM

Narven gravatar image

Narven
49 2 3 10

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first
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 gravatar image

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
(comments are locked)
10|3000 characters needed characters left

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 gravatar image

v0nni
16 1 3

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x573
x355

asked: Apr 27 '10 at 06:24 AM

Seen: 1895 times

Last Updated: Jul 09 '12 at 02:03 PM