Lesson 1.2 - Pedal to the Metal
Overview:
In this lesson you will make your driving simulator come alive. First you will write your very first lines of code in C#, changing the vehicle’s position and allowing it to move forward. Next you will add physics components to your objects, allowing them to collide with one another. Lastly, you will learn how to duplicate objects in the hierarchy and position them along the road
Create and apply your first script
- In the Project window, Right-click > Create > Folder named “Scripts”
- In the “Scripts” folder, Right-click > Create > C# Script named “PlayerController”
- Drag the new script onto the Vehicle object
- Click on the Vehicle object to make sure it was added as a Component in the Inspector
Add a comment in the Update() method
- Double-click on the script to open it in Visual Studio
- In the Update() method, add a comment that you will: // Move the vehicle forward
Give the vehicle a forward motion
- Under your new comment, type transform.tr, then select Translate from the autocomplete menu
- Type (, add 0, 0, 1 between the parentheses, and complete the line with a semicolon (;)
- Press Ctrl/Cmd + S to save your script, then run your game to test it
Use a Vector3 to move forward
- Delete the 0, 0, 1 you typed and use auto-complete to replace it with Vector3.forward
Customize the vehicle’s speed
- Add * Time.deltaTime and run your game
- Add * 20 and run your game
Add RigidBody components to objects
- Select the Vehicle, then in the inspector click Add Component and select RigidBody
- Select the Obstacle, then in the inspector click Add Component and select RigidBody
- In the RigidBody component properties, increase the mass of the vehicle and obstacle to be about what they would be in kilograms and test again
Duplicate and position the obstacles
- Click and drag your obstacle to the bottom of the list in the hierarchy
- Press Ctrl/Cmd+D to duplicate the obstacle and move it down the Z axis
- Repeat this a few more times to create more obstacles
- After making a few duplicates, select one in the hierarchy and hold ctrl + click to select multiple obstacles, then duplicate those