Menu
CoddyTech

Aim with the Paddle

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

With a perfect bounce the player cannot aim. Brick Breaker games let the paddle decide: a hit near the left end sends the ball up and left, a hit in the middle sends it straight up.

Turn the hit into a number from -1 at the left end to 1 at the right: the ball's x offset from the paddle's center, divided by half the paddle's width. A paddle 4 wide centered at x 2, hit at x 3: the offset is 1, half the width is 2, so the number is 0.5 and the ball leaves along (0.5, 1, 0), normalized. Clamp it, since the ball can touch a corner a little past the end.

OnCollisionEnter runs after the physics worked out the bounce, so a velocity set there replaces it. Walls send it too and keep their plain bounce, so check the tag first. collision.collider.bounds.size.x is the paddle's width in the world.

challenge icon

Challenge

Easy

Aim the ball with the paddle: where it lands sets the angle.

  1. In Ball, add OnCollisionEnter(Collision collision); return unless the object hit is tagged Paddle.
  2. Work out float x: the ball's x minus the paddle's x, divided by half of collision.collider.bounds.size.x, clamped between -1 and 1.
  3. Set rb.linearVelocity = new Vector3(x, 1f, 0f).normalized * speed;

Press Play and catch the ball on the paddle's left end: it flies off to the left. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

public class Ball : MonoBehaviour
{
    public Transform paddle;
    public float speed = 9f;

    Rigidbody rb;
    bool launched;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();
        PhysicsMaterial bouncy = new PhysicsMaterial("Bouncy");
        bouncy.bounciness = 1f;
        bouncy.dynamicFriction = 0f;
        bouncy.staticFriction = 0f;
        bouncy.bounceCombine = PhysicsMaterialCombine.Maximum;
        bouncy.frictionCombine = PhysicsMaterialCombine.Minimum;
        GetComponent<Collider>().material = bouncy;
    }

    void Update()
    {
        if (launched) return;
        transform.position = paddle.position + Vector3.up * 0.5f;
        if (Keyboard.current.spaceKey.wasPressedThisFrame) Launch(new Vector3(0.3f, 1f, 0f));
    }

    public void Launch(Vector3 direction)
    {
        launched = true;
        rb.linearVelocity = direction.normalized * speed;
    }

    void FixedUpdate()
    {
        if (!launched) return;
        rb.linearVelocity = rb.linearVelocity.normalized * speed;
    }
}

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground