Asteroids: Quick Overview
Play the game here.
I built this Asteroids clone in JS/HTML Canvas during a flight, as a fun challenge with no internet access while in the airport/on plane on a trip to and from Austin, TX. The game features a basic game loop, game objects, player controls, and collision detection, all rendered on a canvas.
Key Features:
- Canvas-based rendering
- Simple game loop and object system
- Player, asteroids, and bullets as extensions of base GameObject class
- Basic keyboard controls
- Collision and scoring logic
Basic Game Loop:
// Main game loop
function update() {
clearBoard();
for (let obj of gameObjects) {
obj.update();
obj.move();
obj.draw();
}
drawUI();
}
setInterval(update, 33);
GameObject - base class all on-screen items inherit from
class GameObject {
constructor(x, y, initialRotation, initialSpeed, figure, filled) {
this.x = x;
this.y = y;
this.rotation = initialRotation;
this.speed = initialSpeed;
this.figure = figure;
this.filled = filled;
gameObjects.push(this);
}
/**
* Determines the next position of a figure based off its current position and speed
* If object goes off of the edge of a screen, wraps around to other side
*/
move() {
let newX = (this.x + Math.sin(this.rotation) * this.speed);
if (newX < 0) {
newX = canvas.width;
} else if (newX > canvas.width) {
newX = 0;
}
let newY = (this.y - Math.cos(this.rotation) * this.speed);
if (newY < 0) {
newY = canvas.height;
} else if (newY > canvas.height) {
newY = 0;
}
this.x = newX;
this.y = newY;
}
/**
* Draws the gameobject onto the canvas in the corresponding style and position
*/
draw() {
let newFigure = this.getTransformedFigure();
if (this.filled) {
ctx.fillStyle = settings.theme.fgColor;
fillPath(newFigure);
} else {
ctx.strokeStyle = settings.theme.fgColor;
strokePath(newFigure);
}
}
/**
* Returns the positions of the points making up the rotated figure
* Used in drawing to canvas AND collision detection
*/
getTransformedFigure() {
return transformAll(this.figure, this.rotation, this.x, this.y);
}
}
Game objects (player, asteroids, bullets) inherit from the above base class, supplying a figure and handling their own movement and interactions. The player can rotate, thrust, and fire bullets, while asteroids move and detect collisions. Bullets fly straight until they hit something.
For the full code and more details, check out the GitHub repo.
Let me know your high score!