- Home /
Speedometer
Hi, I'm trying to make a simple speedometer so I can keep track of an objects current movement speed. However the one I've made does not display the correct value. Why and how do I fix it?
public float Speed = 1f;
public float topSpeed = 55f;
private float speedMeter = 1f;
// Update is called once per frame
void Update ()
{
transform.position = new Vector2 (transform.position.x + Speed * Time.deltaTime, transform.position.y);
speedMeter = Speed * Time.deltaTime;
}
void OnGUI()
{
GUI.Label(new Rect(10, 70, 300, 100 ), ("speedometer ") + speedMeter + "f");
}
This object is supposed to defy gravity, so no. No rigidbody attached
Answer by robertbu · Feb 19, 2014 at 08:36 AM
Unless some other script modifies it, your speed is constant. It will be 'Speed' every frame. Your 'speedMeter = Speed * Time.deltaTime' is calculating the distance traveled during the specific frame and the result will vary as the frame rate fluctuates. So you can replace 'speedMeter' with 'Speed' in your GUI.Label() call.
Answer by OSG · Feb 19, 2014 at 08:43 AM
You need speedometer when you have acceleration implemented, otherwise speed in your example is a const variable. So you need this:
float accel = 2f;
float minSpeed = 1f;
if(speed < topSpeed) speed += accel; //when object is accelerating
if(speed > minSpeed) speed -= accel; //when object is slowing
I'm working on acceleration, but needed a speedometer to check if it was working
Your answer
![](https://koobas.hobune.stream/wayback/20220613134014im_/https://answers.unity.com/themes/thub/images/avi.jpg)