Here we'll learn how to create a power-up effect—one that allows your spaceship to shoot yellow projectiles in a machine gun-like rhythm. We'll utilize event listeners, object properties, timers, and randomization to achieve this effect.
Our checklist for this feature is:
0:00 Create MachineGunPowerUp class
01:44 Render and move across screen
03:28 Add collision detection and splices
06:49 Activate power up and set timer
08:31 Create machine gun effect
11:08 Change projectile color
12:18 Limit machine gun
13:44 Garbage collection
16:12 Spawn in random locations
update: was able to fix repeating space key shooting using
if (e.repeat) { return }
it returns a boolean specifically if a keyboard event is happening repeatedly
heres the entire function:
addEventListener("keydown", (e) => { if (game.over) return; switch (e.key) { case "a": keys.a.pressed = true; break; case "d": keys.d.pressed = true; break; case " ": keys.space.pressed = true; if (e.repeat) { return; } if (player.powerUp === "MachineGun") return; if (keys.space.pressed) { projectiles.push( new Projectile({ position: { x: player.position.x + player.width / 2, y: player.position.y, }, velocity: { x: 0, y: -10, }, }) ); } break; } });