Meter counter

Please help me because I cant find an answer. I’m new to C# and I struggle to create my first project and Im stuck.
I need a counter of distance player made from start to current position , speed of a player change many times during a game so it must depend only on meters.
My “game” have small open world and player moving on 3D arena
I need a script only for distance he made since start.

I adding super professional drawing to help you guys understand my problem.

First of all, I think your super professional drawing is AWESOME! I immediately understood your problem.

Here is the basic way that you track distance:

At the Start function you take note of your current position.

Each call to Update() you would use Vector3.Distance() to find the distance between those positions.

You would take that tiny amount and add it to another float variable that will accumulate the total distance.

It would look something like this, to measure the distance travelled by the object this script is attached to:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Odometer : MonoBehaviour
{
    Vector3 lastPosition;
    float odometerDistance;

    void Start()
    {
        lastPosition = transform.position;    // write down our initial position
    }

    void Update()
    {
        Vector3 currentPosition = transform.position;    // just make a copy for clarity

        float distance = Vector3.Distance( currentPosition, lastPosition);    // how far?

        odometerDistance += distance;        // accumulate

        lastPosition = currentPosition;    // save your last position for next frame

        // TODO:
        // here you would display the value of
        // odometerDistance somehow, probably using UI.
    }
}

Does that make sense?

4 Likes

It’s working :slight_smile:
Thank you… You made my day. :smile:

1 Like

Hmmm… I have to change my mind… it’s don’t working.

This code don’t give me a meters counter, because when player speeds up counter don’t speeds up with him, it looks like this is just a counter of… time.

Sorry for misunderstanding… here is my movement code, maybe there is something important that cause this is not a meter counter.

void FixedUpdate()
{

transform.Rotate(0, CrossPlatformInputManager.GetAxis(“Horizontal”) * Time.deltaTime * rotationSpeed, 0);
transform.position += transform.forward * Time.deltaTime *movementSpeed;

movementSpeed = Mathf.SmoothDamp(movementSpeed, targetSpeed, ref speedDV, 15.0f);

SpeedMaxValue();

}

void SpeedMaxValue()
{
if (movementSpeed > maxspeed)
{
movementSpeed = maxspeed;
movementSpeed = Mathf.SmoothDamp(movementSpeed, targetSpeed, ref speedDV, 15.0f);
}
}

Check the code formatting again for that post. Also, I don’t see where the odometer code is in your code…

This is just my movement script, odometer is in another one. I post it because maybe my movement system not cooperating with your odometer.