High Speed Chase
Keep your eyes on the road! In this lesson you will code a new C# script for your camera, which will allow it to follow the vehicle down the road and give the player a proper view of the scene. In order to do this, you’ll have to use a very important concept in programming: variables.
Add a speed variable for your vehicle
- In PlayerController.cs, add public float speed = 5.0f; at the top of the class
- Replace the speed value in the Translate method with the speed variable, then test
- Save the script, then edit the speed value in the inspector to get the speed you want
Create a new script for the camera
- Create a new C# script called FollowPlayer and attach it to the camera
- Add public GameObject player; to the top of the script
- Select the Main Camera, then, drag the player object onto the empty player variable in the Inspector
- In Update(), assign the camera’s position to the player’s position, then test
Add an offset to the camera position
- In the line in the Update method add + new Vector3(0, 5, -7), then test
Make the offset into a Vector3 variable
- At the top of FollowPlayer.cs, declare private Vector3 offset;
- Copy the new Vector3() code and assign it to that variable
- Replace the original code with the offset variable
- Test and save
Smooth the Camera with LateUpdate
- Test your prototype to notice the jittering camera as the vehicle drives.
- In FollowPlayer.cs, replace Update() with LateUpdate().
- Save and test to see if the camera is less jittery.
Edit the playmode tint color
- From the top menu, go to Edit > Preferences (Windows) or Unity > Preferences (Mac)
- In the left menu, choose Colors, then edit the “Playmode tint” color to have a slight color
- Play your project to test it, then close your preferences