Menu
CoddyTech

The Paddle

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

In this course you build Brick Breaker in 3D: a paddle at the bottom, a ball that bounces between the walls, and a wall of bricks to break. Each lesson adds one feature: the bricks, lives, levels, a game over screen, and power-ups that widen the paddle or split the ball. The scene is ready: the camera looks at the playfield from the front, and everything moves in the x and y plane at z = 0. The scripts Paddle, Ball, Brick, GameManager and PowerUp are short stubs for now.

The paddle has a kinematic Rigidbody, moved with MovePosition in FixedUpdate, so the physics sees it move and the ball's bounces can use that later. A kinematic body is never stopped by colliders that have no Rigidbody, so the side walls will not hold it back: the script keeps it in. Clamping the center at the wall would leave half the object inside the wall, so the limit is the wall minus half the object's size. This lift car in a shaft from y = 0 to y = 12 does it on y:

float halfHeight = transform.localScale.y / 2f;
Vector3 target = rb.position + Vector3.up * input * liftSpeed * Time.fixedDeltaTime;
target.y = Mathf.Clamp(target.y, 0f + halfHeight, 12f - halfHeight);
rb.MovePosition(target);

Here input is 1 going up, -1 going down and 0 otherwise. A 2 unit tall car keeps its center between 1 and 11, so its ends stop exactly at 0 and 12. A Cube primitive is 1 unit on each side, so localScale.y is the car's height, and reading it every step keeps the limit right if the size changes while the game runs.

challenge icon

Challenge

Easy

Write the paddle's movement in Paddle's FixedUpdate():

  1. Make a float input: -1 while the left arrow or A is held, 1 while the right arrow or D is held, 0 otherwise.
  2. Work out the target: the Rigidbody's position moved right by input * speed * Time.fixedDeltaTime.
  3. Clamp the target's x so the paddle's ends stop at the walls' inner faces, -wallX and wallX. The paddle's width is transform.localScale.x.
  4. Move there with rb.MovePosition.

Press Play, slide the paddle into both walls, 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.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Brick Breaker