Menu
CoddyTech

Launch

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

The ball waits on the paddle until the player launches it. Until then Update() puts it on top of the paddle every frame, so it goes wherever the paddle goes, and a bool remembers whether it has flown:

void Update()
{
    if (launched) return;
    transform.position = paddle.position + Vector3.up * 0.5f;
}

The ball's Rigidbody has no gravity, so a velocity set once keeps it flying straight. wasPressedThisFrame is true only on the frame a key goes down, so read it in Update(). To fly at an exact speed in any direction, make the direction 1 unit long with .normalized, then multiply: new Vector3(3f, 4f, 0f).normalized * 10f flies at 10 units a second.

challenge icon

Challenge

Easy

The ball rides on the paddle until Space launches it.

  1. In Ball, add bool launched; and public void Launch(Vector3 direction): launched = true; and rb.linearVelocity = direction.normalized * speed;
  2. In Update(), return if launched; else put the ball at paddle.position + Vector3.up * 0.5f.
  3. When Space wasPressedThisFrame, call Launch(new Vector3(0.3f, 1f, 0f)).

Press Play, move the paddle, then press Space: the ball flies up and stops on the first wall (bouncing comes next). Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

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

    Rigidbody rb;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Next: the ball rides on the paddle until Space launches it.
}

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground