Skip to content

Instantly share code, notes, and snippets.

@Drewbi
Created January 13, 2024 06:41
Show Gist options
  • Save Drewbi/ac8e520b36297285c822208970448eb7 to your computer and use it in GitHub Desktop.
Save Drewbi/ac8e520b36297285c822208970448eb7 to your computer and use it in GitHub Desktop.
Space Invader Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Space invaders</title>
</head>
<body>
<canvas id="canvas" style="height: 100vh; image-rendering: pixelated; image-rendering: crisp-edges;" width="100"
height="100"></canvas>
</body>
<script src="./main.js"></script>
</html>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d")
const canvasWidth = 100
const canvasHeight = 100
let x = 0
let y = 0
let velocityX = 2
let velocityY = 1
let size = 10
let invaderX = 50
let invaderY = 20
const invaderWidth = 10
const invaderHeight = 5
let invaderDead = false
function eventToGameSpace(e) {
return [
(e.clientX - e.target.offsetLeft) / e.target.clientWidth * canvasWidth,
(e.clientY - e.target.offsetTop) / e.target.clientHeight * canvasHeight
]
}
canvas.addEventListener('click', (e) => {
const [x, y] = eventToGameSpace(e)
if(
isCollided(invaderX, invaderY, invaderWidth, invaderHeight, x, y, 1, 1)
) invaderDead = true;
})
function isCollided(x1, y1, w1, h1, x2, y2, w2, h2) {
return x1 < x2 + w2 &&
x1 + w1 > x2 &&
y1 < y2 + h2 &&
y1 + h1 > y2
}
function invader(x, y, dead) {
ctx.fillStyle = dead ? 'red' : 'white'
ctx.fillRect(x, y, invaderWidth, invaderHeight)
ctx.fillStyle ='red'
ctx.fillRect(x + 3, y + 2, 1, 1)
ctx.fillRect(x + 6, y + 2, 1, 1)
}
function draw() {
ctx.fillStyle ='black'
ctx.fillRect(0, 0, canvasWidth, canvasHeight)
x += velocityX
y += velocityY
if (x > canvasWidth || x < 0) velocityX *= -1
if (y > canvasHeight || y < 0) velocityY *= -1
ctx.fillStyle ='white'
ctx.fillRect(x, y, size, size)
const isDead = isCollided(x, y, size, size, invaderX, invaderY, invaderWidth, invaderHeight)
invader(invaderX, invaderY, isDead || invaderDead)
window.requestAnimationFrame(draw);
}
draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment