Powerup Abilities
Sveip for å vise menyen
Our level is now fully playable but we can make it more interesting by adding powerups.
Powerups introduce variability into gameplay. They can:
- increase
jumpStrength; - change gravity;
- rotate the camera;
- resize the player;
- or anything you design yourself.
In this lesson, we create a powerup that:
- increases
jumpStrengthto20; - makes the player
1.2xbigger; - hides itself after activation;
- resets everything after
5seconds.
Setting Up the Powerup
- add a Powerup
GameObject(e.g., sponge sprite); - add a
Box Collider 2D; - tick Is Trigger;
- attach the
PowerupScript.
Because the collider is set to Is Trigger, we detect interaction using:
OnTriggerEnter2D()
Detecting the Player
Inside OnTriggerEnter2D():
if (collision.gameObject.name == "Player")
This ensures the powerup only activates when the Player touches it.
We also store a reference:
player = collision.gameObject;
This allows us to reset the player later inside the coroutine.
Modifying Jump Strength
jumpStrength lives inside PlatformScript.
If we declare it as public static, we can access it directly from any script:
PlatformScript.jumpStrength = 20;
This increases the player's jump strength immediately when the powerup is collected.
Scaling the Player
We increase the player's size using:
collision.gameObject.transform.localScale *= 1.2f;
This multiplies the player's scale by 1.2 on all axes.
Hiding the Powerup (Without Destroying It)
Instead of destroying the GameObject (which would stop the script), we disable:
GetComponent<SpriteRenderer>().enabled = false;
GetComponent<Collider2D>().enabled = false;
This makes the powerup:
- invisible;
- uninteractable.
But the script continues running, which is important for the reset.
Using a Coroutine for the Delay
We cannot delay inside OnTriggerEnter2D().
Instead, we use a coroutine:
IEnumerator resetVariables()
Inside it:
yield return new WaitForSeconds(5);
After 5 seconds, the following lines execute:
PlatformScript.jumpStrength = 15;
player.transform.localScale /= 1.2f;
This:
- resets jump strength back to its original value (
15); - divides the player's scale by
1.2, restoring the original size.
1. Why did we make jumpStrength public static in PlatformScript?
2. Why did we disable the SpriteRenderer and Collider instead of destroying the powerup?
3. What is the purpose of this line?
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår