LoginSignup
2
3

More than 1 year has passed since last update.

【JavaScript && CSS】今更方向キーで丸を動かす

Posted at

はじめに

JavaScriptでゲームを作る際に必要になる(と思っている)キー入力で何かを動かす操作について、今更ながら調べて実装してみました。

デモ

demo.gif

コード

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>キー入力</title>
    <style>
      #circle {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: blue;
        position: absolute;
        top: 0; /* デモでは調整しています */
        left: 0; /* デモでは調整しています */
      }
    </style>
  </head>
  <body>
    <div id="circle"></div>
    <script>
      const movePx = 5;
      document.addEventListener("keydown", (e) => {
        // 現在の位置を取得、単位を外すためにint化(空文字の場合はNaNになるため0を設定)
        const nowTop =
          parseInt(document.getElementById("circle").style.top) || 0;
        const nowLeft =
          parseInt(document.getElementById("circle").style.left) || 0;

        switch (e.code) {
          case "ArrowUp":
            document.getElementById("circle").style.top =
              nowTop + -movePx + "px";
            break;
          case "ArrowDown":
            document.getElementById("circle").style.top =
              nowTop + movePx + "px";
            break;
          case "ArrowLeft":
            document.getElementById("circle").style.left =
              nowLeft + -movePx + "px";
            break;
          case "ArrowRight":
            document.getElementById("circle").style.left =
              nowLeft + movePx + "px";
            break;
        }
      });
    </script>
  </body>
</html>

おわりに

switch/caseをもっと簡潔に書ける気がするのですが自分の力ではここまででした…
「クン、クーーーーーーーーーーン」と動くのも何とかしたかったのですが、それもよくわからず解決できませんでした。

めちゃくちゃに基礎レベルだと思いますが、参考になりましたら幸いです。

2
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3