Creating a calculator for speed per frame?

Hello.
I wanted to make a calculator that can calculate the amount of speed that an object will increase per frame. The main idea is that if the player’s position in an axis was 1 on the first frame, 2 in the second frame, 5 in the third frame an 8 in the 4th frame, the calculator will display that the player’s speed was 1 in the first and second frames, and 3 in the 3rd and 4th frames. I tried to code it in, but the code didn’t work. Here it is:

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

public class TestScript : MonoBehaviour
{
    void Update()
    {
        Vector3 position = transform.position;
        float speedIncrement;
        float Xpos = position.x;
        Debug.Log(Xpos);
        transform.position = position;
        Xpos = 0;
    }
}

What I wanted to do here is to show the increase in the frame, and then set the value back to 0 before showing the increase in the next frame. Instead, it just displayed my players x axis. I would like to know how to fix this. Thanks.

How are you moving the object?

BTW, what is this for? I don’t see why you would need this information (frame speed)

I’m using AddForce2D, and I’m using AddForce instead of velocity because I want the speed to increase slowly, not go all at once. I want to use this to calculate the correct animation (e.g. If the speed is above 0 but below 1, walk, if it is above 1, run). Thanks.

I think your code should look more like this pseudocode based on your logic

//Find the difference
positionChange = currentPosition - lastPosition

//Make it a positive value if it is negative
speed = Mathf.Abs(positionChange)

//make it frame rate independent (Speed per second?)
speed /= time.deltatime

//Update the last position
lastPosition = currentPosition

the reason that “speed per frame” is not useful is that frame rate is volatile, and different devices run at different frame rates.