How to get proper distance travelled

I’m trying to get the distance travelled by my object every frame in a Vector3, but when I use the code I have currently, I get numbers that are very very wrong and I can’t figure out why.

    private Vector3 lastPosition;
    public Vector3 distanceTravelled;

    void Start()
    {
        lastPosition = mainCamera.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        distanceTravelled = mainCamera.transform.position - lastPosition;
        lastPosition = transform.position;
    }

Use: lastPosition = mainCamera.transform.position; instead of: lastPosition = transform.position;

your code should only work if the camera is moving with the character or the object.

you can create a float variable and increment it for every frame on your input method.
like so

float distanceTravelled;

    void FixedUpdate(){
        if(Input.GetKey(KeyCode.D)){
            rigidbody.velocity += movespeed*Time.deltaTime;
            distanceTravelled += movespeed*Time.deltaTime;
        }
    }

or you can make it into some Vector3 or something. its up to you.
the main thing is, you increment the distance variable when you move the object. NOT every frame.
technically, you do that every frame but, you want to do that for every frame that the object is moving. not just at any frame.