Wide Paddle
Lesson 14 of 16 in Coddy's Unity Game: Brick Breaker course.
A Wide power-up caught with the paddle makes it wider for a few seconds. The power-up notices the catch: its trigger collider touches the paddle's collider, and both bodies are kinematic, which is enough for OnTriggerEnter. It falls through the ball on its way down too, so it checks the tag. An enum with the kinds, set per prefab in the Inspector, tells one power-up from the other.
A timed effect is a coroutine: change, wait, change back. A second catch while the first is still running must start the time again, so keep the Coroutine that StartCoroutine returns and stop it before starting a new one. Otherwise the first one ends early and undoes the second. A speed boost:
Coroutine boost;
public void Boost()
{
if (boost != null) StopCoroutine(boost);
boost = StartCoroutine(BoostFor(3f));
}
IEnumerator BoostFor(float seconds)
{
speed = normalSpeed * 2f;
yield return new WaitForSeconds(seconds);
speed = normalSpeed;
boost = null;
}The boost sets the speed from normalSpeed, remembered once, rather than doubling the current speed and halving it later: two boosts in a row would make that 4 times as fast. The paddle's clamp already reads its width every step, so a wide paddle still stops at the walls.
Challenge
Hard- In
PowerUp, addpublic enum Kind { Wide, Multiball }andpublic Kind kind(each prefab sets its kind). AddOnTriggerEnter: when the power-up touches the object taggedPaddle, a Wide one callsWiden()on that object'sPaddlescript, and either kind destroys the power-up. - In
Paddle, addpublic float wideFactor = 1.6fandpublic float wideSeconds = 8f, and remember the paddle's normal width, its x scale, inAwake(). - Write
public void Widen(): it starts a coroutine that sets the paddle's x scale towideFactortimes the normal width, waitswideSeconds, and sets the normal width back. A catch while wide restarts the time.
A Multiball power-up is caught and does nothing yet.
Press Play, catch a green power-up, then Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
public class Paddle : MonoBehaviour
{
public float speed = 14f;
public float wallX = 8f; // the side walls' inner faces are at -wallX and wallX
Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float input = 0f;
if (Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed) input -= 1f;
if (Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed) input += 1f;
Vector3 target = rb.position + Vector3.right * input * speed * Time.fixedDeltaTime;
float halfWidth = transform.localScale.x / 2f;
target.x = Mathf.Clamp(target.x, -wallX + halfWidth, wallX - halfWidth);
rb.MovePosition(target);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.