# How to Calculate a speed of an Object?

Hello! I’m new to Unity and it’s been almost a week of using it. And it’s been going pre well, also joined the official Discord but people couldn’t find the solution!
So, my request is: How to Calculate the speed of a game object using Distance, position might also be used.

I’ve tried this code but it does’t execute, saying it has no context:

Speed = Vector3.Distance(transform.position, lastPosition.transform.position) / Time.deltaTime;
lastPosition = transform.position;

I’ll be very thankful for any help!

Hello.

You are in one of the right ways.

Does the object have a RigidBody? Beacause if it has RB, you can simple access to `rigidBody.velocity` which is a vector. Just use this to get a float number:

``````float speed = Vector3.Magnitude(rigidBody.velocity)
``````

If does not have a rBody, then yes, you need to store las position, and calculate the distance.

If last position was taken the last frame, you can use time.deltatime as time component.

``````Vector3 lastPosition = Vector3.zero;
float speed = Vector3.Distance(transform.position, lastPosition) / Time.deltaTime;
lastPosition = transfomr.position;
``````

This will calculate speed every frame (except for the first frame, because lastposition will still be empty) and finnaly recalculate the now position as last posotion, and finiosh the frame.

Bye!