Game Development Reference
In-Depth Information
The variable declared in line 28 stores the current speed of the car after applying acceler-
ation, braking, and steering values that come from the player input. Notice that this speed
variable, unlike the previous ones, is expressed in m/s rather than km/h. This is because the
time unit used in Unity is the second, and the distance unit is the meter, which makes deal-
ing with these units easier than the kilometer and the hour. To convert from km/h to m/s, we
use the constant CONVERSION_FACTOR declared in line 32, which has a constant value
of 0.2778. So all we have to do is to multiply any km/h value by CONVERSION_FACTOR
to convert it to m/s. After that, in Start() function, we find the objects RotationAxisR and
RotationAxisL and reference them using rightAxis and leftAxis consequtively, in order to use
them when implementing car turning.
Before getting into the details of Update() function, I want to jump to lines 81 through 90, in
which we declare a custom function called AdjustSpeed() . If you are unfamiliar with program-
ming, we can simply say that declaring functions is useful when you need to repeat the same
task several times in different places, and this task takes a number of lines to program, which
makes writing it over an over tedious and more error prone. And this is the case when
adjusting the speed of the car: we need fi st to add the new value to the current speed, then
check whether the result exceeds the maximum speed, in that case we set the current speed
to the value of maximum speed. We need also to check whether the result is less than zero,
and set the current speed to zero in that case. So what we need to do is to call this function
whenever we want to change the speed of our car, and provide it with newValue that we want
add or subtract from the current speed. Before adding it, newValue need to be converted to
m/s, which is the unit used by AdjustSpeed() .
Search WWH ::




Custom Search