Lesson 1.4 - Step into the Driver's Seat
In this lesson, we need to hit the road and gain control of the vehicle. In order to do so, we need to detect when the player is pressing the arrow keys, then accelerate and turn the vehicle based on that input. Using new methods, Vectors, and variables, you will allow the vehicle to move forwards or backwards and turn left to right.
Allow the vehicle to move left/right
- At the top of PlayerController.cs, add a public float turnSpeed; variable
- In Update(), add transform.Translate(Vector3.right * Time.deltaTime * turnSpeed);
- Run your game and use the turnSpeed variable slider to move the vehicle left and right
Base left/right movement on input
- From the top menu, click Edit > Project Settings, select Input Manager in the left sidebar, then expand the Axes fold-out to explore the inputs
- In PlayerController.cs, add a new public float horizontalInput variable
- In Update, assign horizontalInput = Input.GetAxis("Horizontal");, then test to see it in inspector
- Add the horizontalInput variable to your left/right Translate method to gain control of the vehicle
- In the Inspector, edit the turnSpeed and speed variables to tweak the feel
Take control of the vehicle speed
- Declare a new public forwardInput variable
- In Update, assign forwardInput = Input.GetAxis("Vertical");
- Add the forwardInput variable to the forward Translate method, then test
Make vehicle rotate instead of slide
- Go to Course Library > Obstacles and drag an obstacle directly into the Scene view
- In the Inspector for your obstacle, in the top-right of the Transform component, click the more options button > Reset Position Note: The more options button may appear as three vertical dots or a gear icon, depending on your version of Unity
- In the Inspector, change the XYZ Location to x=0, y=0, z=25
- In the Hierarchy, Right-click > Rename your two objects as “Vehicle” and “Obstacle”
Clean your code and hierarchy
- In the hierarchy, Right-click > Create Empty and rename it “Obstacles”, then drag all the obstacles into it
- Initialize variables with values in PlayerController, then make all variables private (except for the player variables)
- Use // to add comments to each section of code