Crazy Asteroid
Un juego hecho con Canvas y GSAP siguiendo un tutorial de Chris Courses.
Pantalla completa — se abre en una pestaña nueva
Código
HTML
<div class="score"><span>Score: </span><span id="scoreEl">0</span></div>
<canvas></canvas>
<div class="modal" id="modalUI">
<div class="modal__box">
<h1 class="modal__score" id="modalScore">0</h1>
<p class="modal__label">Points</p>
<div>
<button class="modal__btn" id="startGameBtn">Start Game</button>
</div>
</div>
</div>
CSS
/*
* Hand-written replacement for the Tailwind Play CDN the original loaded.
*
* The first half is the slice of Tailwind's preflight these nine elements
* were relying on. The second half is game.html's utility classes, one rule
* per element. Verified against the original by computed style.
*/
*,
::before,
::after {
box-sizing: border-box;
border-width: 0;
border-style: solid;
border-color: #e5e7eb;
}
html {
line-height: 1.5;
-webkit-text-size-adjust: 100%;
font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
}
body {
margin: 0;
line-height: inherit;
background: black;
}
h1,
p {
margin: 0;
}
h1 {
font-size: inherit;
font-weight: inherit;
}
button {
margin: 0;
padding: 0;
font-family: inherit;
font-size: 100%;
font-weight: inherit;
line-height: inherit;
color: inherit;
text-transform: none;
-webkit-appearance: button;
background-color: transparent;
background-image: none;
cursor: pointer;
}
canvas {
display: block;
vertical-align: middle;
}
/* fixed text-white text-sm ml-2 mt-1 select-none */
.score {
position: fixed;
margin-top: 0.25rem;
margin-left: 0.5rem;
font-size: 0.875rem;
line-height: 1.25rem;
color: rgb(255, 255, 255);
user-select: none;
}
/* fixed inset-0 flex items-center justify-center */
.modal {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
}
/* bg-white max-w-md w-full p-6 text-center */
.modal__box {
width: 100%;
max-width: 28rem;
padding: 1.5rem;
background-color: rgb(255, 255, 255);
text-align: center;
}
/* text-4xl font-bold leading-none */
.modal__score {
font-size: 2.25rem;
font-weight: 700;
line-height: 1;
}
/* text-sm text-gray-700 mb-4 */
.modal__label {
margin-bottom: 1rem;
font-size: 0.875rem;
line-height: 1.25rem;
color: rgb(55, 65, 81);
}
/* bg-blue-500 text-white w-full py-3 rounded-full text-sm */
.modal__btn {
width: 100%;
padding-top: 0.75rem;
padding-bottom: 0.75rem;
border-radius: 9999px;
background-color: rgb(59, 130, 246);
font-size: 0.875rem;
line-height: 1.25rem;
color: rgb(255, 255, 255);
}
JS
document.addEventListener("DOMContentLoaded", function () {
console.log(gsap);
const canvas = document.querySelector("canvas");
const c = canvas.getContext("2d");
console.log(canvas);
canvas.width = innerWidth;
canvas.height = innerHeight;
const scoreEl = document.querySelector('#scoreEl');
const startGameBtn = document.querySelector('#startGameBtn');
const modalUI = document.querySelector('#modalUI');
const modalScore = document.querySelector('#modalScore');
class Player {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
draw() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
}
}
class Projectile {
constructor(x, y, radius, color, velocity) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = velocity;
}
draw() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
}
update() {
this.draw();
this.x = this.x + this.velocity.x;
this.y = this.y + this.velocity.y;
}
}
class Enemy {
constructor(x, y, radius, color, velocity) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = velocity;
}
draw() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
}
update() {
this.draw();
this.x = this.x + this.velocity.x;
this.y = this.y + this.velocity.y;
}
}
const friction = 0.98;
class Particle {
constructor(x, y, radius, color, velocity) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = velocity;
this.alpha = 1;
}
draw() {
c.save();
c.globalAlpha = this.alpha;
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
c.restore();
}
update() {
this.draw();
this.velocity.x *= friction;
this.velocity.y *= friction;
this.x = this.x + this.velocity.x;
this.y = this.y + this.velocity.y;
this.alpha -= 0.01;
}
}
const x = canvas.width / 2;
const y = canvas.height / 2;
let player = new Player(x, y, 10, "white");
let projectiles = [];
let enemies = [];
let particles = [];
function init(){
player = new Player(x, y, 10, "white");
projectiles = [];
enemies = [];
particles = [];
score = 0;
scoreEl.innerHTML = 0;
modalScore.innerHTML = 0;
}
// const projectile = new Projectile(
// canvas.width / 2,
// canvas.height / 2,
// 5,
// 'red',
// {
// x:1,
// y:1
// }
// )
function spawnEnemies() {
setInterval(() => {
// valores entre 4 y 30 para que no sean tan chicos
const radius = Math.random() * (30 - 4) + 4;
let x;
let y;
if (Math.random() < 0.5) {
x = Math.random() < 0.5 ? 0 - radius : canvas.width + radius;
y = Math.random() * canvas.height;
} else {
x = Math.random() * canvas.width;
y = Math.random() < 0.5 ? 0 - radius : canvas.height + radius;
}
const color = `hsl(${Math.random() * 360}, 50%, 50%)`;
const angle = Math.atan2(canvas.height / 2 - y, canvas.width / 2 - x);
const velocity = {
x: Math.cos(angle),
y: Math.sin(angle),
};
enemies.push(new Enemy(x, y, radius, color, velocity));
console.log(enemies);
}, 1000);
}
// 51 min
let animationId;
let score = 0;
function animate() {
animationId = requestAnimationFrame(animate);
c.fillStyle = 'rgb(0,0,0, 0.1)';
c.fillRect(0, 0, canvas.width, canvas.height);
player.draw();
particles.forEach((particle, index ) => {
if(particle.alpha <= 0 ){
particles.splice(index, 1);
}else{
particle.update();
}
particle.update();
})
projectiles.forEach((projectile, index) => {
projectile.update();
// remove proyerctiles out view
if(projectile.x + projectile.radius < 0 ||
projectile.x - projectile.radius > canvas.width ||
projectile.y + projectile.radius < 0 ||
projectile.y - projectile.radius > canvas.height){
setTimeout(() => {
projectiles.splice(index, 1);
}, 0);
}
});
enemies.forEach((enemy, index) => {
enemy.update();
const dist = Math.hypot(player.x - enemy.x, player.y - enemy.y);
// end game - game over
if(dist - enemy.radius - player.radius < 1){
cancelAnimationFrame(animationId);
modalUI.style.display = 'flex';
modalScore.innerHTML = score;
}
projectiles.forEach((projectile, projectileIndex) => {
// hypot obtiene distancia entre 2 elementos
const dist = Math.hypot(projectile.x - enemy.x, projectile.y - enemy.y);
// projectile touch enemy
if(dist - enemy.radius - projectile.radius < 1){
// create particles explosions
for (let i = 0 ; i < enemy.radius * 2 ; i++){
// para hacer dandom negativo positivo le resto 0,5
particles.push(
new Particle(
projectile.x,
projectile.y,
Math.random() * 2,
enemy.color,
{
x: (Math.random() - 0.5) * (Math.random() * 6),
y: (Math.random() - 0.5) * (Math.random() * 6)
}
)
)
}
if(enemy.radius - 10 > 5){
// incrase score hit
score += 100;
scoreEl.innerHTML = score;
// enemy.radius -= 10;
gsap.to(enemy,{
radius: enemy.radius - 10, duration: 0.3
});
setTimeout(() => {
projectiles.splice(projectileIndex, 1);
}, 0);
}else{
// incrase score erase enemy
score += 250;
scoreEl.innerHTML = score;
setTimeout(() => {
enemies.splice(index, 1);
projectiles.splice(projectileIndex, 1);
}, 0);
}
}
});
});
}
window.addEventListener("click", (e) => {
console.log(projectiles);
const angle = Math.atan2(event.clientY - canvas.height / 2, event.clientX - canvas.width / 2);
const velocity = {
x: Math.cos(angle)*5,
y: Math.sin(angle)*5,
};
projectiles.push(new Projectile(canvas.width / 2, canvas.height / 2, 5, "white", velocity));
});
startGameBtn.addEventListener("click", (e) => {
init();
animate();
spawnEnemies();
modalUI.style.display = 'none';
});
}); //lave document ready