Menu
CoddyTech

復習:入力の切り替え

CoddyのUnityジャーニー「本格的なゲームを作る」セクションの一部。レッスン 47/56。

challenge icon

チャレンジ

中級

このバブルの杖は古い Input クラス用に書かれています。Both に設定されたプロジェクトでは動作しますが、このプロジェクトは新しい Unity 6 プロジェクトのように設定されています(Active Input Handling: Input System Package)。Play を押すと、最初の Input 呼び出しで InvalidOperationException が発生します。このスクリプトの機能をすべて保ったまま、Input System に移植しましょう。

  • 矢印キーまたは WASD キーで、杖を芝生の上で speed 単位/秒で移動します。斜め移動でも速くなりません。
  • Jump を押すと、杖の 1.5 単位上に泡ができます。Jump を押し続けている間、その泡は毎秒 growRate ずつ、最大 maxSize まで大きくなります。離すと、サイズがログに出力されます(例: Bubble: 0.8)。
  • 左クリックすると、すべての泡がはじけ、個数がログに出力されます(例: Popped 3)。

プロジェクトの Move アクションと Jump アクション、および Mouse.current を使用し、スクリプト内に Input. 呼び出しが残らないようにしてください。Play を押して試し、その後 Check を押してください。

自分で試してみよう

using UnityEngine;

public class Wand : MonoBehaviour
{
    public float speed = 4f;
    public float growRate = 1f;
    public float maxSize = 1.5f;
    public GameObject bubblePrefab;

    private Transform bubble;

    void Update()
    {
        Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        transform.position += move.normalized * speed * Time.deltaTime;

        if (Input.GetButtonDown("Jump"))
        {
            bubble = Instantiate(bubblePrefab, transform.position + Vector3.up * 1.5f, Quaternion.identity).transform;
        }
        if (Input.GetButton("Jump") && bubble != null)
        {
            float size = Mathf.Min(bubble.localScale.x + growRate * Time.deltaTime, maxSize);
            bubble.localScale = Vector3.one * size;
        }
        if (Input.GetButtonUp("Jump") && bubble != null)
        {
            Debug.Log("Bubble: " + bubble.localScale.x.ToString("F1"));
            bubble = null;
        }

        if (Input.GetMouseButtonDown(0))
        {
            GameObject[] bubbles = GameObject.FindGameObjectsWithTag("Bubble");
            foreach (GameObject b in bubbles) Destroy(b);
            Debug.Log("Popped " + bubbles.Length);
        }
    }
}

本格的なゲームを作るのすべてのレッスン