simplestarの技術ブログ

目的を書いて、思想と試行、結果と考察、そして具体的な手段を記録します。

Unity:新しいInputSystemを動かしてみた

■前置き
Unity 2019 のロードマップを確認して、新しい InputSystem が来るヨ
とのことなので、どんなものかだけ触ることにしました。

正式導入は 2019.2 頃なので、2019年9月末ってところです。(予定通りに事が進めば)
その後は現在の Input が廃止されていき、この新しい InputSystem に置き換わります。

これから Unity でゲーム作るぞーって考えている人は、作っている最中にいきなり導入されるだろう新しい InputSystem に驚かないよう
今から少し触っておくのも良いかもしれません。

■導入手順
Unity-Technologies さんの GitHub.com のリポジトリを閲覧し、InputSystem を見つけます。
github.com

README に導入手順が示されているので、この通りに手を動かすと、確かに Input Debugger が機能していることが確認できました。
具体的には…

  1. Copy the Packages/com.unity.inputsystem/ folder to the Packages folder of your own project.
  2. Open the player settings in the editor (Edit >> Project Settings >> Player) and change Active Input Handling* in the 'Configuration' section to either "Both" or "Input System (Preview)". Note that the latter will disable support for the old system and thus render most APIs in UnityEngine.Input non-functional. This will also have impact on systems using the API (e.g. UnityEngine.UI).
  3. Restart the editor.

f:id:simplestar_tech:20181202184114j:plain
Input Debugger の XBox Controller の入力の様子

■一般的な使用方法

まずはREADME に示されている動画を観ます。
www.youtube.com

ここには State, Event, ActionMap の三つの方法についてそれぞれの入力の取り方が示されていました。

一番簡単そうな State のサンプルを試して動きました。

具体的には…
以下のスクリプトを Camera にアタッチしてゲームを再生

using UnityEngine.Experimental.Input;
using UnityEngine;

// Using state of gamepad device directly.
public class SimpleController_UsingState : MonoBehaviour
{
    public float moveSpeed = 3;
    public float rotateSpeed = 100;

    private Vector2 m_Rotation;

    public void Update()
    {
        var gamepad = InputSystem.GetDevice<Gamepad>();
        if (gamepad == null)
            return;

        var leftStick = gamepad.leftStick.ReadValue();
        var rightStick = gamepad.rightStick.ReadValue();

        Move(leftStick);
        Look(rightStick);
    }

    private void Move(Vector2 direction)
    {
        var scaledMoveSpeed = moveSpeed * Time.deltaTime;
        var move = transform.TransformDirection(direction.x, 0, direction.y);
        transform.localPosition += move * scaledMoveSpeed;
    }

    private void Look(Vector2 rotate)
    {
        var scaledRotateSpeed = rotateSpeed * Time.deltaTime;
        m_Rotation.y += rotate.x * scaledRotateSpeed;
        m_Rotation.x = Mathf.Clamp(m_Rotation.x - rotate.y * scaledRotateSpeed, -89, 89);
        transform.localEulerAngles = m_Rotation;
    }
}

ソースは同リポジトリの Assets から持ってきたものです。