[SOLVED] Calculating distance covered

Hello everyone,
I’m currently working on a skill system. The first thing I’m trying to implement is the walking skill.
For this, I need to get the distance the player covered in the last frame.
How would I go about doing that?

Use a Control for that and then in controlUpdate:

a) Sum up getVelocity().length() * tpf;
b) Keep track of a Vector3f oldPos:

``````public void controlUpdate(float tpf) {
float distance = spatial.getLocalTranslation().distance(oldPos);
oldPos = spatial.getLocalTranslation();
}
``````

a) might be more incorrect but quite more efficient.
b) Is the actual traveled distance (independant from bullet’s velocity, important when teleporting!!).

If you don’t have teleports which should count or quite fast velocity changes and gradients (car race), a) should be okay for simple walking.

Test both and compare the results

1 Like

Thank you for the fast answer.
One question though: What is the * tpf in a) for?

The Velocity is in meter/s (or rather “wu/s”, world units per second), however a frame is less than one second (or maybe even 2 seconds long).

So you have s = v * t, whereas t is the tpf (Time per Frame)

If the levelup is calculated every frame though,
I can leave that away, right?
Because I’m adding it to a total distance.

You mean if you check for a levelup every frame?
Not really.

Imagine you drive around with 100m/s (360km/h). The Distance traveled is definately depending on the time between two measures. If you are stunned 1 second, the car traveled 100m, if you are stunned 2 seconds, the car travels 200m.

Similar: If your game runs at 120 FPS, one would have twice the distance than the player at 60 FPS.

1 Like

Now I get it.
Thanks a lot!

1 Like

I’m currently using b) because I only have one walking monkey of which I want to track speed.

The `getLocalTranslation().distance(oldPos);` needs to calculate one square root which used to be slow on old computers. How slow it is today I don’t know, but if it were too slow I would need to use a).

Also, teleporting isn’t important for me, but if it were, I would have to insert special code to compensate for this special case or I would need to use a).

So, there are at least two good reasons not to use b), but to use a). Even if a) might be incorrect when used the wrong way.

Marked topic as [SOLVED].