Detect how many meters an object was moved?

Hi,

does anybode knows how detect the moved meters without a relation to another object?

thanks

you mean something like this ?

Vector3 anchor;
void OnEnable()
{
    anchor = transform.position;
}

void Update()
{
    float distance = Vector3.Distance(anchor,transform.position);
}

Thats not working if i am driving around this…the distance is everytime the same if i drive in a circle because the distance is not changing.

The solution was:

distance += rbody.velocity.magnitude

That solution shouldn’t work in all cases as rbody.velocity is a velocity, not a distance.
Only when you multiply it by time would it become a distance.
distance += (rbody.velocity.magnitude * Time.deltaTime)
Also I wouldn’t even rely on the the rbody.velocity either.
I would do this, keeping track of the last position.

float totalDistanceTraveled;
Vector3 lastPosition;

void Awake()
{
 lastPosition = rbody.transform.position;
}

void Update()
{
totalDistanceTraveled += Vector3.Distance(rbody.transform.position, lastPosition);
lastPosition = rbody.transform.position;
}

…and what if i am driving in a loop? the distance decreased if i am driving back to the startposition, or?

The solution I posted is the sum of all distances traveled per frame, regardless of what direction you are going. Think of it as an odometer of a car.

The solution canis posted is the total displacement since the gameobject became enabled. With his solution, if you traveled around a loop once, the total “distance” would be 0, since you ended up at the same point you started at. With his solution is basically the distance you would need to travel in a straight line to get back to your starting point.

Sorry, it is not 100% clear of the problem you are trying to solve.

yes…exactly…i need the same like an odometer in a car. Thats it.

But in my case its possible to drive around a loop and came back the the same place where i started. Thats why im confused about the “lastPosition” and the distance function, because if im driving back the distance between start and end (if i drive in a loop) is 0… and thats wrong in that case.

The Update() function is called automatically every frame. Essentially your’e calculating how far the car traveled in one frame, and adding that to a totalSum. The lastPosition is to store the position the car was at during the lastFrame, so the distance the car traveled between the current frame and last frame can be determined.

Frame, CurrentPosition, LastPosition, Distance This Frame


1, p2, p1, d1=Distance(p2, p1)
2, p3, p2, d2=Distance(p3, p2)
3, p4, p3, d3=Distance(p4,p3)

TotalDistance = d1+d2+d3

Okay…got it now! Thanks