Catch a Power-Up
Lesson 15 of 19 in Coddy's Unity Game: Brick Breaker course.
A power-up notices the catch itself: its trigger collider touches the paddle's collider, and both bodies are kinematic, which is enough for OnTriggerEnter. It falls past the ball too, so it checks the tag first.
An enum names the kinds, and each prefab sets its own in the Inspector, so one script serves both:
public enum Kind { Wide, Multiball }
public Kind kind;
if (kind == Kind.Multiball) Debug.Log("Three balls");other.GetComponent<Paddle>() finds the Paddle script on the object the power-up touched. Widen only logs for now; the next lesson makes the paddle grow.
Challenge
HardCatch a falling power-up with the paddle.
- In
PowerUp, addpublic enum Kind { Wide, Multiball }andpublic Kind kind;(each prefab sets its kind). - Add
OnTriggerEnter(Collider other): return unlessother.CompareTag("Paddle"); a Wide one callsother.GetComponent<Paddle>().Widen();, thenDestroy(gameObject); - In
Paddle, addpublic void Widen()that logsWide paddlefor now.
Press Play and catch a green one: it vanishes and the Console shows Wide paddle. 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);
}
}
All lessons in Unity Game: Brick Breaker
Practice on your own: Unity playground