Refining the Ball Bounce Logic

Right now the Ball class has its own constructor, but it does not do anything beyond what the parent Sprite constructor already does. Let’s clean that up and then fix a subtle collision bug in the bounce method.

Removing the Redundant Constructor

Delete the constructor from the Ball class entirely. When a subclass omits its constructor, the parent class’s constructor is inherited automatically. This is different from languages like Java, where you must explicitly declare non-default constructors.

Refactoring the Bounce Method

Now update the bounce method so it checks both horizontal and vertical edges of the canvas:

bounce(canvasWidth, canvasHeight) {
  if (this.x < 0 || this.x > canvasWidth) {
    // bounce off the left/right edges
    this.dx *= -1; // switch direction
  }

  if (this.y < 0 || this.y > canvasHeight) {
    // bounce off the top/bottom edge
    this.dy *= -1; // switch direction
  }
}

Save your code and look at the result in the browser. The ball sinks a little into the right and bottom edges before it changes direction. That happens because the collision check uses only the ball’s top-left corner and does not account for its width and height.

Accounting for Ball Dimensions

To fix this, add this.width and this.height to the boundary checks:

  bounce(canvasWidth, canvasHeight) {
-   if (this.x < 0 || this.x > canvasWidth) {
+   if (this.x < 0 || this.x + this.width > canvasWidth) {
      // bounce off the left/right edges
      this.dx *= -1; // switch direction
    }

-   if (this.y < 0 || this.y > canvasHeight) {
+   if (this.y < 0 || this.y + this.height > canvasHeight) {
      // bounce off the top/bottom edge
      this.dy *= -1; // switch direction
    }
  }

Save and check in the browser. The ball now bounces off every edge without sinking in.

Checkpoint: Commit your progress.

git add .
git commit -m "brick-08: Refine ball bounce logic and fix edge collision"
git push