LoginSignup
0
2

More than 1 year has passed since last update.

Unityでキーボードによるゲーム操作

Last updated at Posted at 2021-09-15

Input.GetKey

ほとんどのプログラミング例にはこのInput.GetKeyが使われてます。
たとえばこんな感じ。

float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");

WASDと↑←↓→キー両方どちらの入力も取得してくれてます。
これはHorizontalが水平、つまり左右。
Verticalが上下の入力ですね。

問題点

2DSTGを作ろうとしてて気づいたのが、入力が貯まるということ。
テストプレイをして、自機が滑るような、あるいは慣性がついているような?キーを離したのにまだ少し動くという現象がありました。
Rigidbodyのせいかとも思ったのですが、最終的にRigidbodyを外してもやはり滑る。
そこでキー入力自体を検証していたら、キーボードの入力がある程度貯まるということに気が付きました。
キーボードを押しっぱなしにしている間に連射のように入力が蓄積されていくんですね。

解決

キーが下がった時とキーが上がった時をきちんと判定したら問題なく滑らなくなりました。

        if((Input.GetKeyDown(KeyCode.A)) || (Input.GetKeyDown(KeyCode.LeftArrow)))
        {
            x1 =  -1;
        }
        if ((Input.GetKeyDown(KeyCode.D)) || (Input.GetKeyDown(KeyCode.RightArrow)))
        {
            x2 =  1;
        }
        if ((Input.GetKeyDown(KeyCode.W)) || (Input.GetKeyDown(KeyCode.UpArrow)))
        {
            y1 = 1;
        }
        if ((Input.GetKeyDown(KeyCode.S)) || (Input.GetKeyDown(KeyCode.DownArrow)))
        {
            y2 = -1;
        }

        if ((Input.GetKeyUp(KeyCode.A)) || (Input.GetKeyUp(KeyCode.LeftArrow)))
        {
            x1 = 0;
        }
        if ((Input.GetKeyUp(KeyCode.D)) || (Input.GetKeyUp(KeyCode.RightArrow)))
        {
            x2 = 0;
        }
        if ((Input.GetKeyUp(KeyCode.W)) || (Input.GetKeyUp(KeyCode.UpArrow)))
        {
            y1 = 0;
        }
        if ((Input.GetKeyUp(KeyCode.S)) || (Input.GetKeyUp(KeyCode.DownArrow)))
        {
            y2 = 0;
        }


        float x = x1 + x2;
        float y = y1 + y2;

もっとうまい書き方もあるかと思いますが、こういう理屈なのだということが参考になればと思います。
(移動の左右切り替えのときに引っかかるような感じがした(おそらく右キーを離すのと左キーを押すのがほぼ同時の時に判定がおかしくなる)ので、コードの例を修正しました。

0
2
0

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
0
2