<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> body {
margin:0;
}
#escenario {
position: relative;
margin:auto;
background-color:black;
color: white;
width:100vmin;
height:100vmin;
overflow: hidden;
}
#personaje {
position:absolute;
width: 8vmin;
height: 8vmin;
top: 46vmin;
left: 46vmin;
transform: rotate(0deg);
}
const MITAD = 4;
let pacman;
let x = 50, y = 50;
function iniciar() {
pacman = document.getElementById('personaje');
document.addEventListener('keydown', moverPersonaje);
}
function moverPersonaje(evento) {
const offset = obtenerDireccion(evento.key);
const angle = obtenerRotacion(event.key);
x += offset.x*1.5;
y += offset.y*1.5;
pacman.style.left = (x-MITAD) + 'vmin';
pacman.style.top = (y-MITAD) + 'vmin';
pacman.style.transform = `rotate(${angle}deg)`;
if (x < -MITAD) x = 100+MITAD; else if (x > 100+MITAD) x = -MITAD;
if (y < -MITAD) y = 100+MITAD; else if (y > 100+MITAD) y = -MITAD;
}
function obtenerDireccion(flecha) {
switch (flecha) {
case 'ArrowLeft': return {x:-1, y:0};
case 'ArrowRight': return {x:1, y:0};
case 'ArrowUp': return {x:0, y:-1};
case 'ArrowDown': return {x:0, y:1};
default: return {x:0, y:0};
}
}
function obtenerRotacion(flecha) {
switch (flecha) {
case 'ArrowLeft': return 180;
case 'ArrowRight': return 0;
case 'ArrowUp': return -90;
case 'ArrowDown': return 90;
default: return 0;
}
}
<body onload="iniciar()"> <p>Pulsa las flechas de dirección para mover el personaje
</p> <img id="personaje" src="pacman_right.gif">