Qui c'è un esempio spartano di come si potrebbe essere fatto. Notte
codice:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>gina che si muove attorno a giannozza</title>
<style>
.controlli {
z-index: auto;
display: grid;
grid-template-columns: 50px 50px 50px;
grid-template-rows: auto;
grid-template-areas:
"testo testo testo"
". su ."
"sx . dx"
". giu .";
}
#titolo {
grid-area: testo;
text-align: center;
}
#bottoneSu {
grid-area: su;
}
#bottoneGiu {
grid-area: giu;
}
#bottoneDestra {
grid-area: dx;
}
#bottoneSinistra {
grid-area: sx;
}
#gina {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid black;
z-index: -1;
}
#giannozza {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="controlli">
<h3 id="titolo">Controlli</h3>
<button id="bottoneSu">SU</button>
<button id="bottoneGiu">GIU</button>
<button id="bottoneDestra">DX</button>
<button id="bottoneSinistra">SX</button>
</div>
<div id="gina"></div>
<div id="giannozza"></div>
<script>
// risoluzione finestra browser
const xMax = window.innerWidth
const yMax = window.innerHeight
// bottoni
const btnUp = document.getElementById('bottoneSu')
const btnDown = document.getElementById('bottoneGiu')
const btnRight = document.getElementById('bottoneDestra')
const btnLeft = document.getElementById('bottoneSinistra')
// contenitori
const gina = document.getElementById('gina')
const giannozza = document.getElementById('giannozza')
// eventi click
btnUp.addEventListener('click', spostaSu)
btnDown.addEventListener('click', spostaGiu)
btnRight.addEventListener('click', spostaDestra)
btnLeft.addEventListener('click', spostaSinistra)
// evento keydown
document.body.addEventListener('keydown', fnKeys)
// posizioni iniziale
gina.style.top = `${(yMax / 2) - 205}px`
gina.style.left = `${(xMax / 2) - 100}px`
giannozza.style.top = `${(yMax / 2 - 100)}px`
giannozza.style.left = `${(xMax / 2 - 100)}px`
// fn movimento
function spostaSu() {
if (parseInt(gina.style.top) <= 0) return
let tmpValue = parseInt(gina.style.top)
gina.style.top = `${tmpValue - 25}px`
}
function spostaGiu() {
if (parseInt(gina.style.top) >= yMax - 125) return
let tmpValue = parseInt(gina.style.top)
gina.style.top = `${tmpValue + 25}px`
}
function spostaSinistra() {
if (parseInt(gina.style.left) <= 0) return
let tmpValue = parseInt(gina.style.left)
gina.style.left = `${tmpValue - 25}px`
}
function spostaDestra() {
if (parseInt(gina.style.left) >= xMax - 125) return
let tmpValue = parseInt(gina.style.left)
gina.style.left = `${tmpValue + 25}px`
}
// tasti comando (cursore/pad numerico)
function fnKeys(e) {
switch (e.keyCode) {
case 38:
case 104:
spostaSu()
break;
case 40:
case 98:
spostaGiu()
break;
case 39:
case 102:
spostaDestra()
break;
case 37:
case 100:
spostaSinistra()
break;
}
}
</script>
</body>
</html>