movimiento

This commit is contained in:
Marklogo 2024-03-22 13:44:28 +01:00
parent cb9ec99cdc
commit 7a08b80e87

45
game.js
View File

@ -4,6 +4,8 @@ const ctx = canvas.getContext("2d");
const width = (canvas.width = 288);
const height = (canvas.height = 512);
const sprites = [];
const background = new Image();
background.src = "./assets/bg.png";
@ -26,14 +28,23 @@ class Suelo {
}
class Tuberia {
constructor(ctx) {
constructor(ctx, posX, tipo) {
this.ctx = ctx;
this.tuberiaImg = new Image();
this.tuberiaImg.src = "./assets/tuberias.png";
this.tipo = tipo;
this.width = 52;
this.height = 320;
this.separacion = 60; //min 60 max 120
this.posX = width / 2;
this.posX = posX;
this.posY =
Math.floor(Math.random() * (300 - 100 + 1)) +
100 -
Math.floor(this.height * 2 + this.separacion) / 2;
}
generaPos() {
this.posX = width;
this.posY =
Math.floor(Math.random() * (300 - 100 + 1)) +
100 -
@ -41,14 +52,17 @@ class Tuberia {
}
update() {
//this.posX--;
this.posX--;
if (this.posX <= 0 - this.width) {
this.generaPos();
}
}
draw() {
this.ctx.drawImage(
this.tuberiaImg,
1 * this.width,
0,
this.tipo * this.height,
this.width,
this.height,
this.posX,
@ -59,7 +73,7 @@ class Tuberia {
this.ctx.drawImage(
this.tuberiaImg,
0 * this.width,
0,
this.tipo * this.height,
this.width,
this.height,
this.posX,
@ -75,6 +89,7 @@ class Bird {
animFrame = 0;
gameFrame = 0;
constructor(ctx) {
this.gravedad = 0;
this.ctx = ctx;
this.birdImg = new Image();
this.birdImg.src = "./assets/flappybird.png";
@ -84,6 +99,7 @@ class Bird {
this.height = 24;
}
update() {
this.posY += this.gravedad;
this.animFrame = Math.floor(this.gameFrame / 10) % this.nFramesAnim;
this.gameFrame++;
}
@ -105,18 +121,19 @@ class Bird {
function gameLoop(timeStamp) {
ctx.clearRect(0, 0, width, height);
ctx.drawImage(background, 0, 0, width, height);
bird.update();
bird.draw();
tuberia.update();
tuberia.draw();
suelo.update();
suelo.draw();
sprites.forEach((sprite) => {
sprite.update();
sprite.draw();
});
requestAnimationFrame(gameLoop); // Llamar a gameLoop de nuevo en el siguiente fotograma
}
const suelo = new Suelo(ctx);
const bird = new Bird(ctx);
const tuberia = new Tuberia(ctx);
sprites.push(
new Bird(ctx),
new Tuberia(ctx, width * 2, 1),
new Tuberia(ctx, width * 2 + width * 0.5 + 25, 0),
new Suelo(ctx)
);
window.onload = () => {
gameLoop();