Basic GamePlay
In this Unit, you will program a top-down game with the objective of throwing food to hungry animals - who are stampeding towards you - before they can run past you. In order to do this, you will become much more familiar with some of the most important programming and Unity concepts, including if-then statements, random value generation, arrays, collision detection, prefabs, and instantiation. In completing this Unit, you will learn how to program a basic game with the ability to launch projectiles and maneuver the player to keep the game alive.
Create a new Project for Prototype 2
- Open Unity Hub and create an empty “Prototype 2” project in your course directory on the correct Unity version. If you forget how to do this, refer to the instructions in Lesson 1.1 - Step 1
- Click to download the Prototype 2 Starter Files, extract the compressed folder, and then import the .unitypackage into your project. If you forget how to do this, refer to the instructions in Lesson 1.1 - Step 2
- From the Project window, open the Prototype 2 scene and delete the SampleScene
- In the top-right of the Unity Editor, change your Layout from Default to your custom layout
Add the Player, Animals, and Food
- If you want, drag a different material from Course Library > Materials onto the Ground object
- Drag 1 Human, 3 Animals, and 1 Food object into the Hierarchy
- Rename the character “Player”, then reposition the animals and food so you can see them
- Adjust the XYZ scale of the food so you can easily see it from above
Get the user’s horizontal input
- In your Assets folder, create a “Scripts” folder, and a “PlayerController” script inside
- Attach the script to the Player and open it
- At the top of PlayerController.cs, declare a new public float horizontalInput
- In Update(), set horizontalInput = Input.GetAxis(“Horizontal”), then test to make sure it works in the inspector
Move the player left-to-right
- Declare a new public float speed = 10.0f;
- In Update(), Translate the player side-to-side based on horizontalInput and speed
Keep the player inbounds
- In Update(), write an if-statement checking if the player’s left X position is less than a certain value
- In the if-statement, set the player’s position to its current position, but with a fixed X location
Clean up your code and variables
- Repeat this process for the right side of the screen
- Declare new xRange variable, then replace the hardcoded values with them
- Add comments to your code