Показать сообщение отдельно
  #6 (permalink)  
Старый 27.09.2018, 15:09
Аватар для SuperZen
Профессор
Отправить личное сообщение для SuperZen Посмотреть профиль Найти все сообщения от SuperZen
 
Регистрация: 08.11.2017
Сообщений: 641

<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 = {}
    let previousKeyPressed = {}
    const currentPosition = {
      x: 100,
      y: 100
    }

    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)) {
        delete keyPressed[e.keyCode]
      }
    })

    setInterval(() => {
      document.getElementById('keys').value = JSON.stringify(keyPressed)
      document.getElementById('previous_keys').value = JSON.stringify(previousKeyPressed)
      update()
    }, 100)

    update = () => {
      if (38 in keyPressed && !(38 in previousKeyPressed)) currentPosition.y -= speed
      if (40 in keyPressed && !(40 in previousKeyPressed)) currentPosition.y += speed

      if (37 in keyPressed && !(37 in previousKeyPressed)) currentPosition.x -= speed
      if (39 in keyPressed && !(39 in previousKeyPressed)) currentPosition.x += speed

      hero.style.top = `${currentPosition.y}px`
      hero.style.left = `${currentPosition.x}px`

      previousKeyPressed = { ...keyPressed }
    }
  </script>
</body>

</html>
Ответить с цитированием