Drops
Lesson 13 of 16 in Coddy's Unity Game: Brick Breaker course.
A broken brick sometimes drops a power-up that falls toward the paddle. Whether it drops is a roll: Random.value is a random float from 0 to 1, so Random.value < 0.15f is true about 15 times in 100. Keeping the chance in a field lets you tune it, and lets a test set it to 1 for a drop every time or to 0 for none.
Which power-up drops is a second roll: a random index into an array of prefabs. Random.Range with ints leaves out its maximum, so Random.Range(0, array.Length) can pick every element. An enemy's loot:
public GameObject[] loot;
public float lootChance = 0.25f;
void DropLoot()
{
if (Random.value >= lootChance) return;
int pick = Random.Range(0, loot.Length);
Instantiate(loot[pick], transform.position, Quaternion.identity);
}A power-up falls at a steady speed by moving itself every frame, and destroys itself once it is below the play area, so missed ones do not pile up. Its prefab has a kinematic Rigidbody and a trigger collider, so the physics knows it moves and it will be able to tell when it reaches the paddle.
Challenge
Hard- In
PowerUp, addpublic float fallSpeed = 3fandpublic float bottomY = -9f. InUpdate(), move down atfallSpeedunits a second, and destroy the power-up once its y is belowbottomY. - In
GameManager, addpublic GameObject[] powerUps(the scene links the WidePowerUp and MultiPowerUp prefabs) andpublic float dropChance = 0.15f. - In
BrickBroken, with a chance ofdropChance, make a random one ofpowerUpswhere the brick was.
The power-ups fall through the paddle for now: catching them comes next.
Press Play, break bricks until one drops, then Check.
Try it yourself
using UnityEngine;
public class PowerUp : MonoBehaviour
{
// The last chapter: power-ups that fall from broken bricks.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.