- Home /
Odometer for a racing game
Hello! I'm working on a racing game with a long distance explore/campain mode. I have a speedometer with a working needle, but I think it will add a touch of realism to have a GUIText odometer underneath it. I have a GUIText object created, but no code to go with it.
My car does have a rigidbody attached. I'm not sure if I can use rigidbody.position or a similar method to display the mileage in a GUIText form.
I'm sorry that I don't have any sample code, being relatively new to racing games! Thank you in advance for any answers/comments/suggestions you may have!
Edit: I'm sorry for referring to the odometer as "kilometer" before and for any confusion it may have caused!
Answer by rutter · Aug 30, 2014 at 05:04 AM
Well, is the car traveling in a straight line? If so, you just need to calculate the distance between your starting location and wherever you're at, now.
private var startPosition : Vector3;
function Start() {
startPosition = transform.position;
}
function Update() {
float distance = Vector3.Distance(startPosition, transform.position);
}
On the other hand, what if your car's path is twisting and turning constantly? Well, in that case you could estimate the distance it travels during each frame.
private var totalDistance : float;
private var lastPosition : Vector3;
function Start() {
lastPosition = transform.position;
}
function Update() {
float frameDistance = Vector3.Distance(lastPosition, transform.position);
totalDistance += frameDistance;
lastPosition = transform.position;
}
Thank you! I made some $$anonymous$$or adjustments to the script to display the value as text. I'll put them here in case any other Unity users run into the same problem in the future. Simply add:
`public var odometer :GUIText;
//Put in the Update function to display the distance accurately each frame.
odometer.text = totalDistance + " $$anonymous$$eters Traveled";`
Another line can be added to convert meters into miles/kilometers and display it smoothly.
Thank you for solving this problem and for your prompt answer!
Answer by Kiwasi · Aug 30, 2014 at 05:14 AM
Another option is to integrate velocity each frame.
TotalDistance += rigidbody.velocity.magnitude * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Can I arbitrarily move a dynamic Rigidbody 2D? 1 Answer
Best way to find triangle that a given point occupies. 1 Answer
calculate the estimated distance travel based on the Force applied to Rigid Body 1 Answer
Distance along one axis? 1 Answer
Display countdown timer in Unity: distance traveled C# 1 Answer