Hi there I making a game where my character runs. I have been searching to learn how to make a counter that would show me my speed in real time( km/h ).
Thanx
Hi there I making a game where my character runs. I have been searching to learn how to make a counter that would show me my speed in real time( km/h ).
Thanx
You have two kind of speeds, rigidbody.velocity which (the magnitude) in unit / physic deltaTime, or how much will physics move the object during the next physic loop, and the one you have to calculate yourself, (lastPos-currPos).magnituge, which is unit / regular deltaTime if done in Update and unit / physic deltaTime from FixedUpdate. That's the theory.
Now, what you want to display will probably be
float speed;
// Update is called once per frame
void FixedUpdate () {
speed = rigidbody.velocity.magnitude; // Unit / physic dt
speed *= Time.fixedDeltaTime; // Unit / s, fixedDeltaTime being 1 / physic dt
}
void OnGUI()
{
GUI.Label( new Rect(10, 10, 300, 100 ), speed + " Unit/s" );
GUI.Label( new Rect(10, 30, 300, 100 ), (speed * 3600) + " Unit/h" );
GUI.Label( new Rect(10, 50, 300, 100 ), (speed * 3600 / 1000) + " KUnit/h" );
}
Now, it's up to you to consider one Unit to be a meter or not. By the way, you might want to use coroutine to get an average value for that, just to smooth it out.
I believe you could do something like this for an object that isn't a rigidbody:
#pragma strict
private var initialPosition : Vector3;
private var myT : Transform;
function Start () {
myT = transform;
initialPosition = myT.position;
}
function Update () {
var magnitude : float = (myT.position - initialPosition).magnitude / Time.deltaTime;
initialPosition = myT.position;
Debug.Log(magnitude);
}