Player constructor()
The constructor runs once when a new Player object is created. It initializes all the spaceship's properties: position, size, movement speed, and shooting mechanics. These properties are stored as 'this' variables so every method in the class can access and modify them.
constructor() {
this.width = 40;
this.height = 30;
this.x = width / 2 - this.width / 2; // Center horizontally
this.y = height - 50; // Near the bottom
this.speed = 5;
this.bullets = [];
this.lastShotTime = 0;
this.shotDelay = 200; // Milliseconds between shots
}
Line-by-line explanation (8 lines)
this.width = 40;- Sets the spaceship's width to 40 pixels—this is used for drawing the triangle and keeping it on-screen.
this.height = 30;- Sets the spaceship's height to 30 pixels—helps define the triangle shape and collision bounds.
this.x = width / 2 - this.width / 2; // Center horizontally- Positions the spaceship at the horizontal center of the canvas by subtracting half its width from the canvas center.
this.y = height - 50; // Near the bottom- Places the spaceship 50 pixels from the bottom of the screen, leaving room for the bottom boundary.
this.speed = 5;- Sets how many pixels the spaceship moves each time move() is called—higher values make it move faster.
this.bullets = [];- Initializes an empty array to store all active bullets fired by the player.
this.lastShotTime = 0;- Tracks the time of the last shot in milliseconds, used to enforce the shooting delay.
this.shotDelay = 200; // Milliseconds between shots- Sets the minimum time in milliseconds between consecutive shots—prevents bullet spam and balances game difficulty.