Game Development Reference
In-Depth Information
We need to attach this script to each one of the four visual wheels of our vehicle. We have
two variables that need to be set from the inspector: wheel , which references the input
wheel collider; from which the data is going to be read (RPM, steer angle, and suspen-
sion), and steeringAxis ; which is the axis of vertical rotation of the visual wheel. This ver-
tical rotation reflects the steer angle of the wheel, and hence is needed only for the front
wheels. Before discussing the details of the script, we have to add two new empty objects
to the hierarchy of our vehicles. These objects are SteeringAxis_L and SteeringAxis_R . As the
names suggest, these objects are going to be the axes for steering rotation, so they must be
positioned at the left and right ends of FrontAxis . Now we have to specify the appropriate
source of data for each one of the four wheels, as well as the appropriate steering axes for
the front wheels.
Back to the script, we have two additional variables: lastSteerAngle , which stores the
steering angle from the previous frame, and originalPos , which stores the original position
of the wheel when Start() function is called. Since this script performs animation tasks, the
best practice is to update it using LateUpdate() ; in order to make sure that all objects have
updated state before animating them. The first task is straightforward, which is the spinning
of the wheels. All we have to do is to read RPM values from the wheel collider, convert its
value from minutes to seconds, and then use the converted value to rotate the wheel around
its local y axis (remember that the wheel is a cylinder laying on its side, so the its local y
axis goes from left to right). This rotation is performed in line 31.
If steeringAxis variable is not null , we update the steer angle of the wheel based on the steer
angle of the collider. This task is performed through two steps: reset and set. The first step
is to reset the rotation of the wheel back to straight position, which can be done by rotating
the wheel around the local y axis of steeringAxis by the amount of -lastSeerAngle . Now we
have to set the new steer angle by rotating the wheel around the same axis, but this time by
amount equal to wheel.steerAngle , which is the current steer angle of the collider. Finally,
we store the value of current steer angle in lastSteerAngle , to be able to reset the value in
the next frame. Keep in mid that steeringAxis for the back wheels is null , so this step is not
applicable to these wheels.
Finally, we have to update the y position of the wheel based on the state of the suspension
spring. If you have already tested the vehicle, you might have noticed that some the wheels
sink into the ground. This is a result of applying a pressure on the suspension springs, which
Search WWH ::




Custom Search