4-Mover-personaje
Flujo del programa
- Al cargar la página, se ejecuta
inicializa()gracias al atributoonloaddel<body>. inicializa()configura el canvas y define un bucle de actualización usandosetInterval.- La función
principal()se ejecuta 50 veces por segundo:- Limpia el canvas.
- Dibuja los tres personajes.
- Actualiza sus posiciones según sus velocidades y direcciones.
- Los personajes se mueven horizontalmente de un lado a otro, cambiando de dirección al alcanzar los bordes definidos (
50a400en el eje X).
Resultado:
Tres cuadrados amarillos que se mueven horizontalmente a diferentes velocidades, rebotando entre los límites del canvas.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body onload="inicializa()">
<canvas id="canvas" width="500" height="300" style="border:2px solid #000000">
</canvas>
<script>
console.log("moverpersonaje")
var canvas;
var ctx;
var FPS = 50;
console.log("FPS", FPS);
console.log("hola");
var personaje = function (x, y) {
this.x = x;
this.y = y;
this.derecha = true;
this.dibuja = function () {
ctx.fillStyle = "#fff000";
ctx.fillRect(this.x, this.y, 50, 50);
};
this.mueve = function (velocidad) {
if (this.derecha == true) {
if (this.x < 400) {
this.x += velocidad;
} else {
this.derecha = false;
}
} else {
if (this.x > 50) {
this.x -= velocidad;
} else {
this.derecha = true;
}
}
};
};
function inicializa() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
setInterval(function () {
principal();
}, 1000 / FPS); // Corrección aquí
}
var per1 = new personaje(10, 50);
var per2 = new personaje(10, 120);
var per3 = new personaje(10, 230);
function borraCanvas() {
canvas.width = 500;
canvas.height = 400;
}
function principal() {
borraCanvas();
per1.dibuja();
per2.dibuja();
per3.dibuja();
per1.mueve(1);
per2.mueve(3);
per3.mueve(70);
// console.log("funcion");
}
</script>
</body>
</html>

Comentarios
Publicar un comentario