Extending Block with a Sprite Class
Our Block can draw itself, but it cannot move. In a brick-breaker game, the ball and the paddle both need to move across the canvas. We could copy all of Block’s code into a new class and add movement properties to the copy. Inheritance lets us avoid that duplication.
Creating the Sprite Subclass
Create a new file sprite.js in the src/model folder:
import Block from "./block.js";
class Sprite extends Block {
constructor(x, y, width, height, color, dx, dy) {
super(x, y, width, height, color);
this.dx = dx;
this.dy = dy;
}
move() {
this.x += this.dx;
this.y += this.dy;
}
}
export default Sprite;
Understanding Inheritance
The extends keyword makes Sprite a subclass of Block. This means a Sprite automatically has all the properties and methods of Block (like x, y, and draw) without rewriting them.
The super(...) call inside the constructor invokes the parent class’s constructor. It passes along the shared properties (x, y, width, height, color) so Block can initialize them. You must call super before using this in a subclass constructor.
Modeling Movement with Velocity
The two new properties, dx and dy, represent the sprite’s velocity vector. This is how far it moves on each frame along the x and y axes. The move() method updates the sprite’s position by adding that velocity to its coordinates.
| Property | Purpose |
|---|---|
dx |
Horizontal speed (pixels per frame) |
dy |
Vertical speed (pixels per frame) |
move() |
Shifts position by (dx, dy) each call |
Checkpoint: Commit your progress.
git add .
git commit -m "brick-05: Add Sprite class extending Block with movement"
git push