# How to get the speed of an object?

So I know that you can get the velocity from the rigidBody. And I tried this. The problem I’m having, is that when I collide with an object, blocking the player, the velocity doesn’t come back as 0, instead it is as if the player never stopped moving. Same thing happen’s in reverse, when something collides with the player, causing it to move, the rigidBody.velocity still returns as greater than zero. Same thing happens in reverse. So when an object collides with the player while the player is standing still, causing it to move, the velocity returns as 0. I’m guessing it is because I change the velocity parameter of the player using the on screen controls. So how can I make it so that the player’s speed comes back as 0 when he collides with something, and also make it not come back as zero when something else pushes the player?

I tried using:

``````speed = (transform.position - lastPosition).magnitude / Time.deltaTime;
lastPosition = transform.position;
``````

But if I put it in the Update, it mostly comes back as 0 regardless if the player is moving or not. In LateUpdate, it will come back as zero every other Update. And in the FixedUpdate, it will work correctly for like 2 seconds, but then it starts throwing 2’s for no reason.

This should work:

float speed;
Vector3 oldPosition;

``````void FixedUpdate()
{
speed = Vector3.Distance(oldPosition, transform.position) * 100f;
oldPosition = transform.position;

Debug.Log("Speed: " + speed.ToString("F2"));
}
``````

You could try

``````speedPerSec = Vector3.Distance (oldPosition, transform.position) / Time.dealtTime;
speed = Vector3.Distance (oldPosition, transform.position);
oldPosition = transform.position;
``````

but I don’t see how it would really make a difference.

NOTE: I wrote both speed and speedPerSec, but you can just remove one of them and the other won’t be affected.

Thanks torigas! Using AddForce was almost the right thing, but does greatly improve the way my player moves overall. It was still a bit odd, and I had to achieve my desired effect in a completely different way than I had previously tried. But after long hours, I finally achieved what I was aiming for. Thank you everyone for your help

I get different results with the Debug.Log output when viewing in full screen game mode or just a small window. How can I make this exact same value with all screen sizes and frame rate?