Game Development Reference
In-Depth Information
1. using UnityEngine;
2. using System.Collections; 3.
4. public class CarSpeedMeasure : MonoBehaviour { 5.
6.
public WheelCollider wheel; 7.
8.
void Start () { 9.
10.
}
11.
12.
void Update () {
13.
//Print the speed in the console
14.
print (GetCarSpeed());
15.
}
16.
17.
//Converts RPM to Km/h based on
18.
//the radius of the wheel
19.
float GetCarSpeed(){
20.
//Meters per minute
21.
float mpm = wheel.rpm * wheel.radius * 2 * Mathf.PI;
22.
//Meters per hour
23.
float mph = mpm * 60;
24.
//Kilometers per hour
25.
float kmph = mph / 1000;
26.
return kmph;
27.
}
28.}
Listing 45: A script to measure current vehicle speed in km/h
Notice that the script needs a reference to one of the wheel colliders, since the measured
speed is based on the current RPM of the wheels. Once again we use the circumference of
the wheel, in order to calculate the distance traveled every complete rotation. Recall that
we already have a camera script for car racing games, which is CarCamera (Listing 13).
Search WWH ::




Custom Search