Menu
CoddyTech

The Paddle

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

In this course you build Brick Breaker in 3D, a feature a lesson: a paddle, a bouncing ball, a wall of bricks, lives, levels and power-ups. Everything moves in the x and y plane at z 0. The scripts Paddle, Ball, Brick, GameManager and PowerUp are stubs for now. Play runs the game; Check grades it.

The paddle has a kinematic Rigidbody, moved with rb.MovePosition in FixedUpdate(), so the physics sees it move. A kinematic body goes through the walls, so the script keeps it in. Clamping the center at the wall would leave half the paddle inside it: the limit is the wall minus half the width. With walls at -6 and 6 and a paddle 2 wide:

float half = 2f / 2f;
target.x = Mathf.Clamp(target.x, -6f + half, 6f - half);
rb.MovePosition(target);

The center stays between -5 and 5, so the ends stop exactly at the walls. Reading the width from transform.localScale.x every step keeps the limit right if the paddle grows.

challenge icon

Challenge

Easy

Move the paddle between the walls.

  1. In Paddle's FixedUpdate(), make float input: -1 while the left arrow or A is held, 1 for the right arrow or D, else 0.
  2. Work out Vector3 target = rb.position + Vector3.right * input * speed * Time.fixedDeltaTime;
  3. With float half = transform.localScale.x / 2f;, clamp target.x between -wallX + half and wallX - half, then rb.MovePosition(target);

Press Play and slide into both walls: the paddle stops at each. 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()
    {
        // Move with the arrows or A and D, and stay between the walls.
    }
}

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground