- Home /
Having a speed counter
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
Answer by save · Feb 22, 2012 at 11:05 PM
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); }
Don't know if you see the edited version (doesn't update the answer for me), you should be able to simply use:
#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);
}
Answer by Berenger · Feb 22, 2012 at 10:27 PM
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.
Your answer
Follow this Question
Related Questions
Timer Pause 1 Answer
Problem with speed boost 2 Answers
Marquee.cs speeds up scrolling with keydown 1 Answer
hide gui.label after an event 1 Answer
Car speedometer MPH 1 Answer