Ладно, тогда, последний "не работающий" пример... ))
<html>
<head>
<style>
#hero {
position: fixed;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background-color: burlywood;
border: 1px dashed #cccccc;
}
</style>
</head>
<body>
<textarea id="keys"></textarea>
<textarea id="previous_keys"></textarea>
<div id="hero"></div>
<script>
const keys = [37, 39, 38, 40]
const speed = 5
const keyPressed = {}
const previousKeyPressed = {}
const currentPosition = {
x: 100,
y: 100
}
keys.forEach(key => keyPressed[key] = previousKeyPressed[key] = false)
const hero = document.getElementById('hero')
document.addEventListener('keydown', function (e) {
e.preventDefault()
if (keys.includes(e.keyCode)) {
keyPressed[e.keyCode] = true
}
})
document.addEventListener('keyup', function (e) {
e.preventDefault()
if (keys.includes(e.keyCode)) {
keyPressed[e.keyCode] = false
}
})
setInterval(() => {
document.getElementById('keys').value = JSON.stringify(keyPressed)
document.getElementById('previous_keys').value = JSON.stringify(previousKeyPressed)
update()
}, 100)
update = () => {
if (keyPressed[38] && !previousKeyPressed[38]) currentPosition.y -= speed
if (keyPressed[40] && !previousKeyPressed[40]) currentPosition.y += speed
if (keyPressed[37] && !previousKeyPressed[37]) currentPosition.x -= speed
if (keyPressed[39] && !previousKeyPressed[39]) currentPosition.x += speed
hero.style.top = `${currentPosition.y}px`
hero.style.left = `${currentPosition.x}px`
Object.keys(keyPressed).forEach(key => previousKeyPressed[key] = keyPressed[key])
}
</script>
</body>
</html>