Step 12

Let's build a paddle so we can hit the ball with it! Moreover, we would like to move the paddle 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, 0, 0);
    this.displacement = 7;
    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 = this.displacement;
    } else if (e.key === "Left" || e.key === "ArrowLeft") {
      this.dx = -this.displacement;
    }
  }

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

export default Paddle;

The keyDownHandler is invoked when you press a key down. If that key is the left or right arrow, then the paddle trajectory and displacement are updated so it would appear to move left or right. When you let go of the left or right arrow keys, the keyUpHandler is called to stop the paddle's motion.

The methods keyDownHandler and keyUpHandler use 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. Instead, it is the execution context of addEventListener. Therefore, we need to explicitly bind their this keyword to the Paddle object when passing them as an argument to addEventListener. This point is much harder to figure out on your own had I not told you about it 😜.

Update the main.js file as follows:

  • 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 and observer the changes in the browser.