Distance Counter

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ANDYORSEN

Hello, I’m working on a 3d project and I want to make a path counter so that it counts x and z units traveled. I’m new to godot and I’ve only worked on 2d projects before, so it’s hard for me to even write code that captures every unit of the path traveled and adds that unit as traveled. There are tutorials on the Internet that calculate the distance between two objects, but this is not what I need… I would be very happy to help.

:bust_in_silhouette: Reply From: Inces

Of course it is about the distance between two points. Every path consists of portions of distance traveled towards specific directions. You should incorporate distance calculation from tutorial into your movement system, so every step taken adds a value to total path travelled, from step start to step end.

:bust_in_silhouette: Reply From: jgodfrey

First, you’ll need to define what you mean by “distance traveled”. For example, let’s assume we have 2 points that are 10 units apart (pointA and pointB). If the player moved from pointA to pointB (in a straight line), they’ve obviously moved 10 units. However, what if the player moves from pointA to pointB and then back to pointA. Is that 20 units or 0 units? I assume 20 units, but your answer will impact how you go about coding for this.

Really, this is about continuously calculating the distance between 2 points - you just need to decide on the proper sampling rate or trigger. Some examples:

You could simply have a timer that fires at regular intervals (say, every second or so). When the timer fires, you could calculate the distance between the player’s current point and their previous point (when the timer fired last time) and add it to your running “total distance”. That’d be really easy, and if your sample rate is high enough, it’d be relatively accurate. Obviously, it’d miss minor overlapped movements that happened between intervals.

Another way might be motion based. Each frame you’re somehow (already) calculating how far to move the player based on input events. Once that value is known, use it not only to move the player, but also add it to the running total. This would also be easy and should be very accurate.

To get more specific input (such as code suggestions), I’d suggest that you share your current movement code, as that second idea will likely need to be integrated there…