Step 10

Let's build a paddle so we can hit the ball with! First, however, we'll make it so we can move it around with the arrow- keys on the keyboard.

Create a file model/Paddle.js which the following content:

import Sprite from "./Sprite.js";

class Paddle extends Sprite {
  constructor(x, y, width, height, color) {
    super(x, y, width, height, color);
    this.dx = 0;
    document.addEventListener("keydown", this.keyDownHandler.bind(this));
    document.addEventListener("keyup", this.keyUpHandler.bind(this));
  }

  keyDownHandler(e) {
    if (e.key === "Right" || e.key === "ArrowRight") {
      this.dx = 7;
    } else if (e.key === "Left" || e.key === "ArrowLeft") {
      this.dx = -7;
    }
  }

  keyUpHandler(e) {
    if (e.key === "Right" || e.key === "ArrowRight") {
      this.dx = 0;
    } else if (e.key === "Left" || e.key === "ArrowLeft") {
      this.dx = 0;
    }
  }

  move() { /* overriding the move method */
    super.move(this.dx, 0);
  }
}

export default Paddle;

Note how I used event listeners to move the paddle around when a user presses the left/right arrow keys.

Update the script.js:

  • Import Paddle.js
    import Paddle from "./model/Paddle.js";
    
  • Create a Paddle
    const paddle = new Paddle(
      (canvas.width - 10) / 2,
      canvas.height - 10,
      75,
      10,
      "#0095DD"
    );
    
  • Draw and move it in the draw method:
    paddle.draw(ctx);
    paddle.move();
    

Save your code again and try it in your browser.

Exercise: remove bind(this) inside addEventListener statements. Save your code again and try it in your browser. What happens and why?

Solution

The methods keyDownHandler and keyUpHandler make use of the this keyword to update the properties of Paddle. However, when they are called by addEventListener, their execution context is not the Paddle object anymore (it is the execution context of addEventListener). We need to explicitly bind their this keyword to the Paddle object when we pass them as argument to addEventListener.

This point is much harder to figure out on your own, had I not told you about it 😜.