Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have 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;

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

1
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

Comments

No comments

Let's comment your feelings that are more than good

Qiita Conference 2024 Autumn will be held!: 11/14(Thu) - 11/15(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

Takahiro Anno, Masaki Fujimoto, Yukihiro Matsumoto(Matz), Shusaku Uesugi / Nicolas Ishihara(Vercel Inc.)

View event details

Being held Article posting campaign

1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address