Game Development Reference
In-Depth Information
The first step in Start() function is to make sure that the camera is at the same position
of the car, and is looking to the same direction of the front vector of the car. Therefore
we copy the values from the position and the rotation of the car to the position and the
rotation of the camera. It is a good time now to briefly discuss the programmatic concept
of copying the value and copying the reference. In case of copying the value, like our case
in Start() function, the variables involved remain independent of each other after copying is
completed. This means that any future change on car.position or car.rotation is not going to af-
fect the camera, which is not the case when copying by reference. However, I am not going to
discuss reference copy unless it is the appropriate time to do so.
Notice that in line 37 we use LateUpdate() instead of Update() , in order to make sure that
Unity executes the logic of CarController first and updates the position of the car before
executing CarCamera, which makes the camera follow it (you can go back to page 30 for
more on LateUpdate() ). In lines 40 and 45, we position the camera in its correct place
relative to the car. We perform this through two steps: firstly we position the camera at the
same position of the car (line 40), then we use transform.Translate() to move it backwards
and upwards using zDistance and height . We use the negative value of zDistance to have the
camera move backwards and be behind the car, based on the left hand rule as always.
After updating the position of the camera, it is time to update the rotation. The first step is
to get the angle between the car front direction car.forward , and the direction at which the
camera is looking transform.forward . The forward vector of any object points to the positive
direction of the local z axis of that object. We perform angle measurement in line 48, and
store the angle value in angle variable. It is important to mention here that Vector3.Angle()
measures the angle between the two given vectors, and returns the minimum possible angle
between them. The returned angle is always positive, regardless of the order in which
vectors are passed to the function.
All following steps in lines 53 through 85 are related to camera rotation after the car turns.
These steps depend on having an angle between the car front and the direction of the cam-
era, which is greater than one degree. This condition is checked in line 53 before moving
to the next steps. These steps begin by testing the value of angleChangeTime , and reset it to
zero if its is equal to -1 (lines 56 through 58). After that, in line 62, we accumulate the time
passed since last frame to the value of angleChangeTime . In line 64 we check whether the
Search WWH ::




Custom Search