Menu
CoddyTech

Launch

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

The ball waits on the paddle until the player launches it. Until then the script puts it on top of the paddle every frame, so it goes wherever the paddle goes, and a bool remembers whether it has been launched. The launch sets the Rigidbody's linearVelocity once. The ball's Rigidbody has gravity turned off, so from then on it flies in a straight line at that velocity until it hits something.

A fishing float works the same way: it hangs under the rod's tip until the cast.

bool cast;

void Update()
{
    if (cast) return;
    transform.position = rodTip.position + Vector3.down * 1.5f;
    if (Keyboard.current.spaceKey.wasPressedThisFrame)
    {
        cast = true;
        rb.linearVelocity = new Vector3(4f, 3f, 0f);
    }
}

wasPressedThisFrame is true only on the frame the key goes down, so it is read in Update(), which runs once every frame. The float flies at the length of (4, 3, 0), 5 units a second. To launch at an exact speed in any direction, make the direction 1 unit long with .normalized, then multiply it by the speed.

challenge icon

Challenge

Easy

In Ball:

  1. Add a bool launched.
  2. Write public void Launch(Vector3 direction): it sets launched to true and the Rigidbody's linearVelocity to the direction made 1 unit long, times speed.
  3. Add Update(). While the ball is not launched, it puts the ball 0.5 units above the paddle's position, and when Space is pressed it calls Launch(new Vector3(0.3f, 1f, 0f)).

The ball has no bounce yet, so it stops dead on the first wall it hits: the next lesson fixes that.

Press Play, move the paddle, launch, 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.
}
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