Menu
CoddyTech

Wide Paddle

Lesson 16 of 19 in Coddy's Unity Game: Brick Breaker course.

A timed effect is a coroutine: change, wait, change back. A second catch while the first is running must start the time again, so keep the Coroutine that StartCoroutine returns and stop it before starting a new one. Otherwise the first ends early and undoes the second. A speed 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;
}

It sets the speed from normalSpeed, kept once, rather than doubling the current speed: two boosts in a row would make that 4 times as fast. The paddle's clamp reads its width every step, so a wide paddle still stops at the walls.

challenge icon

Challenge

Hard

A Wide power-up makes the paddle wider for 8 seconds.

  1. In Paddle, add public float wideFactor = 1.6f; and public float wideSeconds = 8f;, and keep the normal x scale in Awake.
  2. Widen() stops the running coroutine, if any, and starts one: x scale wideFactor times normal, wait wideSeconds, normal again.
  3. The coroutine needs using System.Collections;.

Press Play and catch a green one: the paddle grows, then shrinks back. 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);
    }

    public void Widen()
    {
        Debug.Log("Wide paddle");
    }
}

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground