Breakout Clone 1: Adding a ball, a paddle, and walls

The ball starts off with an initial velocity of (1, 1); up and to the right. Having it "bounce" off the walls and paddle is as simple as adding colliders to everything through Unity's interface, setting the isTrigger flag, and then adding an OnTriggerEnter2D method to a script attached to the Ball game object:

  private void OnTriggerEnter2D (Collider2D other) {
    switch(other.tag) {
      case "Left Wall":
        SideWallHit();
        break;
      case "Right Wall":
        SideWallHit();
        break;
      case "Top Wall":
        TopWallHit();
        break;
      case "Paddle":
        PaddleHit();
        break;
      default:
        BottomHit();
        break;
    }
  }

  private void SideWallHit() {
    rigidBody2D.velocity = rigidBody2D.velocity * new Vector2(-1, 1);
  }

  private void TopWallHit() {
    rigidBody2D.velocity = rigidBody2D.velocity * new Vector2(1, -1);
  }

  private void PaddleHit() {
    rigidBody2D.velocity = rigidBody2D.velocity * new Vector2(1, -1);
  }

This is extremely rough logic, and I'm very certain that there is a way to do this with colliders only. I can already foresee problems with this when I go to introduce blocks. The Ball can collide with a block on the top, bottom, or sides, and should bounce away in the appropriate direction. Even now, if the ball were to strike the right or left side of the paddle, it would reflect back up towards the middle of the game area.

Moving the paddle itself is much more straightforward:

  void Update() {
    int horizontal = 0;
    horizontal = (int) Input.GetAxisRaw("Horizontal");
    Vector2 vec = new Vector2(horizontal * paddleMoveSpeed, rigidBody2D.velocity.y);

    rigidBody2D.velocity = vec;
  }

This should theoretically work with a joystick on a controller as well, but I'm developing on my Macbook, which is all USB-C, and my controllers are all USB type A 😬.

Published: 2023-02-01