Stage 4: Sun and Sunflowers
Objective 🧐🗿
In this lesson, we're going to illuminate our game world by making suns drop from the sky and sunflowers generate suns. Before we start, let's create a plant script for both the peashooter and the upcoming sunflower.
Coach Note!
These are the topics you will be going over for this stage:
Standard
- Health and Damage Mechanics: Implementing and managing health variables for game objects and handling damage through methods.
- Layer Management in Unity: Understanding and utilizing layers to manage interactions and collisions in Unity.
- Object Pooling for Efficient Resource Management: Techniques for creating and managing a pool of reusable objects to optimize performance.
Advanced
- Raycasting for Object Interaction: Using raycasts to detect and interact with objects in a 2D space based on player input.
- Coroutine Usage for Timing and Delays: Implementing coroutines to manage timed actions and delays within Unity scripts.
- Dynamic Object Spawning and Management: Creating and controlling the behavior of dynamically spawned objects, including positioning and destruction based on conditions.
Step 1 - Set Up the Plant Script 🌳📜
1.1 Initialize Variables
📝 Pseudocode for Plant Script:
Plant Class:
Declare variables:
- health: an integer to store the health of the plant
- tile: a Transform indicating the tile where the plant is placed
1.2 Start Method
Start method:
- Set the layer of the gameObject to 9 (or another specified layer for interaction within Unity)
1.3 Hit Method
We need to handle the case were the plant gets hit
Hit method:
- The hit method should take in an int known as damage as a parameter
- Take the health and subtract it by the damage
- Make an if statement that checks if health is below or equal to 0
- Inside the if statement check if the tile is not equal to null
- If true then get the tile and set hasPlant to false
- After that if statement destroy the gameObject
Ensure each plant in Unity has an assigned health value.
Step 2 - Sun Drops and Sunflowers 🌞🌻
2.1 Create Sun Objective
Create a new object for the sun:
-
Components: Sprite Renderer, Box Collider 2D, Sun Script
-
Sprite: Choose an image that looks sunny!
2.2 Initialize Variables
📝 Sun Script Pseudocode:
SunScript Class:
Declare variables:
- dropDownPosition: a float indicating the y-coordinate to which the sun should drop
- speed: a float set to 1.4f to control the movement speed of the sun
- targetPosition: a Vector3 to store the target position where the sun should stop
- hasReachedTarget: a boolean to track whether the sun has reached its target position
2.3 Start and Update Methods
Start method:
- Set targetPosition based on the current x and z positions of the sun but use dropDownPosition for the y-coordinate
- Destroy the gameObject after a random time between 9 and 15 seconds
Update method:
- If the sun has not yet reached the target position:
- Move the sun towards the target position at a rate of 'speed * Time.deltaTime'
- Check if the distance between the current position and target position is less than 0.01
- If true, set 'hasReachedTarget' to true indicating the sun has stopped moving
Step 3 - Create the SunSpawner 🌞📦
3.1 Create a Sun Spawner Object
Place a SunSpawner object above the lawn and put a script inside it.
3.2 Initializing variables
📝 Sun Spawner Pseudocode:
SunSpawner Class:
Declare variables:
- sunObject: a GameObject reference for the sun object to be spawned
3.3 Start Method
Start method:
- Schedule the SpawnSun method to be called after a random delay between 3 and 9 seconds
3.4 Spawn Sun Method
SpawnSun method:
- Instantiate a new sunObject at a random x-coordinate between -4.71 and 6.9, y-coordinate fixed at 6, and z-coordinate fixed at 0 with no rotation (Quaternion.identity)
- Set the dropDownPosition of the instantiated sun to a random y-coordinate between 2 and -3
- Schedule the SpawnSun method to be called again after a random delay between 3 and 9 seconds
Step 4 - Edit the GameManager 🎮👨💼
4.1 Change the Update Method
Modify the GameManager to collect suns using a raycast and mouse interaction.
📝 GameManager Pseudocode:
Modify the GameManager to collect suns using a raycast and mouse interaction.
Update method:
- Check if the left mouse button is pressed
- Create a ray from the camera through the mouse position
- Perform a raycast in 2D to detect if any object with a specific mask (sunMask) is hit
- If an object is hit by the raycast:
- Increase the suns counter by 25 (presumably, suns act as a resource or score)
- Destroy the object that was hit (removing the sun from the scene)
Step 5 - Create the Sunflower 🌻📦
5.1 Creating the Sunflower Object
Duplicate the peashooter object, replace its sprite with a sunflower, and modify the script for sun production.
5.2 Initializing Variables
📝 Sun Script Pseudocode:
SunFlower Class:
Declare variables:
- sunObject: a GameObject reference for the sun object to be spawned
- cooldown: a float representing the time between spawns
5.3 Start Method
Start method:
- Schedule the SpawnSun method to be called repeatedly every 'cooldown' seconds starting after the first 'cooldown' period
5.4 Spawn Sun Method
SpawnSun method:
- Calculate the drop position to be half a unit below the current y-coordinate of the SunFlower
- Instantiate a new sunObject at the calculated position with no rotation (Quaternion.identity)
Medium: Add Sunflower Animation!
Goal: Implement interactive behaviors for the sun and sunflower.
6.1 Gather your assets
Search online for sunflower assets to animate! Preferably a sunflower sheet with a different image for each frame.
6.2 Editing the sheet
Use the sprite editor and slice the sheet file, then replace the existing sunflower object's sprite with the sunflower sheet.
6.3 Animate
Use the animation editor to create an animation! Simply drag the images onto the editor and click play until the animation looks right.
Hard: Dynamic Sunflower Behaviors
Goal: Enhance sunflower mechanics for advanced gameplay.
- Variable Sun Production: Make sun production rates vary based on the time of day in-game. Sunflowers produce more frequently when it is first planted and gradually the production speed decreases or increases.
- Sunflower Limitations: Set the maximum number of sunflowers that are allowed to be planted to make the user think twice before spam buying sunflowers.
- Ensure both the sunflower and the peashooter are functioning correctly before moving on. In the next session, we'll focus on enabling zombies to attack our plants.