<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>
<div id="hero"></div>
<script>
const keys = [37, 39, 38, 40]
const speed = 5
const keyPressed = {}
const currentPosition = {
x: 100,
y: 100
}
const hero = document.getElementById('hero')
document.addEventListener('keydown', function (e) {
if (keys.includes(e.keyCode)) {
keyPressed[e.keyCode] = true
}
})
document.addEventListener('keyup', function (e) {
if (keys.includes(e.keyCode)) {
delete keyPressed[e.keyCode]
}
})
setInterval(() => {
document.getElementById('keys').value = JSON.stringify(keyPressed)
update()
}, 100)
update = () => {
if (38 in keyPressed) currentPosition.y -= speed
if (40 in keyPressed) currentPosition.y += speed
if (37 in keyPressed) currentPosition.x -= speed
if (39 in keyPressed) currentPosition.x += speed
hero.style.top = `${currentPosition.y}px`
hero.style.left = `${currentPosition.x}px`
}
</script>
</body>
</html>
у меня как-то так получилось )